@hop-top/kit 0.5.0-alpha.2 → 0.5.0-alpha.3

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.
@@ -0,0 +1,1257 @@
1
+ /**
2
+ * Tests for the serve hierarchy and service lifecycle.
3
+ *
4
+ * The contract these pin is `docs/contracts/serve-lifecycle.md`,
5
+ * §"Cross-language parity". Where a value is cross-language (a topic
6
+ * string, an exit code, the name grammar) it is asserted as a literal
7
+ * rather than against the implementation's own constant, so a change to
8
+ * the constant does not silently take the assertion with it.
9
+ */
10
+
11
+ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
12
+ import { Command } from 'commander';
13
+ import { execFileSync, spawn } from 'node:child_process';
14
+ import { rmSync, writeFileSync } from 'node:fs';
15
+ import * as path from 'node:path';
16
+
17
+ import {
18
+ DEFAULT_FAILURE_POLICY,
19
+ DEFAULT_READY_TIMEOUT_MS,
20
+ DEFAULT_SHUTDOWN_TIMEOUT_MS,
21
+ DEFAULT_STOP_TIMEOUT_MS,
22
+ NAME_PATTERN,
23
+ RESERVED_NAMES,
24
+ ServiceRegistrationError,
25
+ LoopKeepAlive,
26
+ ServiceRegistry,
27
+ Supervisor,
28
+ codeFor,
29
+ defaultTopics,
30
+ exitCodeFor,
31
+ isFailure,
32
+ isReservedName,
33
+ applyEnableDisable,
34
+ applyTimeoutOverrides,
35
+ parseDurationMs,
36
+ registerServe,
37
+ resolve,
38
+ signalController,
39
+ startOrder,
40
+ validateName,
41
+ worstOutcome,
42
+ type EventPayload,
43
+ type LifecycleOutcome,
44
+ type Publisher,
45
+ type Service,
46
+ type ServiceConfig,
47
+ } from './serve.js';
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // Helpers
51
+ // ---------------------------------------------------------------------------
52
+
53
+ interface FakeOptions {
54
+ /** Reject from start with this message instead of serving. */
55
+ failStartWith?: string;
56
+ /** Never call ready(), so the readiness budget decides. */
57
+ neverReady?: boolean;
58
+ /** Return from start (cleanly) after this many ms rather than on abort. */
59
+ returnAfterMs?: number;
60
+ /** Reject from start after readiness — a runtime crash. */
61
+ crashAfterMs?: string;
62
+ /** Hang in stop rather than resolving, so the stop budget decides. */
63
+ hangInStop?: boolean;
64
+ /** Reject from stop with this message. */
65
+ failStopWith?: string;
66
+ validate?: () => string | null;
67
+ dependsOn?: string[];
68
+ addr?: string;
69
+ cls?: [string, string];
70
+ }
71
+
72
+ /** A service whose whole lifecycle is scriptable from the test. */
73
+ function fakeService(name: string, o: FakeOptions = {}): Service & {
74
+ startCount: number; stopCount: number; stopOrder: number[];
75
+ } {
76
+ const state = { ready: false, startCount: 0, stopCount: 0, stopOrder: [] as number[] };
77
+ const svc: Service = {
78
+ name,
79
+ async start(signal, ready) {
80
+ state.startCount++;
81
+ if (o.failStartWith) throw new Error(o.failStartWith);
82
+ if (!o.neverReady) {
83
+ state.ready = true;
84
+ ready();
85
+ }
86
+ if (o.returnAfterMs !== undefined) {
87
+ await sleep(o.returnAfterMs);
88
+ return;
89
+ }
90
+ if (o.crashAfterMs !== undefined) {
91
+ await sleep(1);
92
+ throw new Error(o.crashAfterMs);
93
+ }
94
+ await abortPromise(signal);
95
+ },
96
+ ready: () => state.ready,
97
+ async stop() {
98
+ state.stopCount++;
99
+ state.stopOrder.push(stopSequence++);
100
+ if (o.failStopWith) throw new Error(o.failStopWith);
101
+ if (o.hangInStop) await new Promise<void>(() => { /* never settles */ });
102
+ state.ready = false;
103
+ },
104
+ };
105
+ if (o.validate) svc.validate = o.validate;
106
+ if (o.dependsOn) svc.dependsOn = () => o.dependsOn!;
107
+ if (o.addr !== undefined) svc.addr = () => o.addr!;
108
+ if (o.cls) svc.class = () => o.cls!;
109
+ // Defined as accessors, not Object.assign: assign copies a getter's
110
+ // *value* at call time, which would freeze every counter at 0.
111
+ return Object.defineProperties(svc, {
112
+ startCount: { get: () => state.startCount, enumerable: true },
113
+ stopCount: { get: () => state.stopCount, enumerable: true },
114
+ stopOrder: { get: () => state.stopOrder, enumerable: true },
115
+ }) as Service & { startCount: number; stopCount: number; stopOrder: number[] };
116
+ }
117
+
118
+ let stopSequence = 0;
119
+
120
+ const sleep = (ms: number): Promise<void> =>
121
+ new Promise((r) => { const t = setTimeout(r, ms); t.unref?.(); });
122
+
123
+ const abortPromise = (signal: AbortSignal): Promise<void> =>
124
+ new Promise((r) => {
125
+ if (signal.aborted) { r(); return; }
126
+ signal.addEventListener('abort', () => r(), { once: true });
127
+ });
128
+
129
+ /** A registry pre-loaded with the named services. */
130
+ function registryOf(...svcs: Service[]): ServiceRegistry {
131
+ const r = new ServiceRegistry();
132
+ for (const s of svcs) r.register(s);
133
+ return r;
134
+ }
135
+
136
+ /** Collects every published event so a test can assert on the trace. */
137
+ function recorder(): Publisher & { events: Array<{ topic: string; payload: EventPayload }> } {
138
+ const events: Array<{ topic: string; payload: EventPayload }> = [];
139
+ return {
140
+ events,
141
+ publish(e) { events.push({ topic: e.topic, payload: e.payload }); },
142
+ };
143
+ }
144
+
145
+ /** A run signal that aborts after `ms`, standing in for SIGTERM. */
146
+ function abortAfter(ms: number): AbortSignal {
147
+ const ac = new AbortController();
148
+ const t = setTimeout(() => ac.abort(), ms);
149
+ t.unref?.();
150
+ return ac.signal;
151
+ }
152
+
153
+ const enabled = (...names: string[]): Record<string, ServiceConfig> =>
154
+ Object.fromEntries(names.map((n) => [n, { enabled: true }]));
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // Naming
158
+ // ---------------------------------------------------------------------------
159
+
160
+ describe('service names', () => {
161
+ it('accepts the contract grammar', () => {
162
+ for (const name of ['api', 'socket', 'a', 'a1', 'a-b', 'mcp-stdio']) {
163
+ expect(NAME_PATTERN.test(name), name).toBe(true);
164
+ expect(validateName(name), name).toBeNull();
165
+ }
166
+ });
167
+
168
+ it('rejects anything outside it', () => {
169
+ for (const name of ['', 'API', '1api', '-api', 'api_v2', 'api.v2', 'a b']) {
170
+ expect(validateName(name), name).not.toBeNull();
171
+ }
172
+ });
173
+
174
+ it('reserves exactly all, none and list', () => {
175
+ expect([...RESERVED_NAMES].sort()).toEqual(['all', 'list', 'none']);
176
+ for (const n of ['all', 'none', 'list']) {
177
+ expect(isReservedName(n)).toBe(true);
178
+ // A reserved word matches the grammar but is still refused: the
179
+ // two rules are independent.
180
+ expect(NAME_PATTERN.test(n)).toBe(true);
181
+ expect(validateName(n)).toContain('reserved');
182
+ }
183
+ expect(isReservedName('api')).toBe(false);
184
+ });
185
+ });
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Registration seam
189
+ // ---------------------------------------------------------------------------
190
+
191
+ describe('ServiceRegistry', () => {
192
+ it('lists in registration order', () => {
193
+ const r = registryOf(fakeService('zeta'), fakeService('alpha'), fakeService('mid'));
194
+ expect(r.names()).toEqual(['zeta', 'alpha', 'mid']);
195
+ expect(r.list().map((s) => s.name)).toEqual(['zeta', 'alpha', 'mid']);
196
+ expect(r.size).toBe(3);
197
+ });
198
+
199
+ it('refuses a duplicate name at registration', () => {
200
+ const r = registryOf(fakeService('api'));
201
+ expect(() => r.register(fakeService('api'))).toThrow(ServiceRegistrationError);
202
+ // Last-writer-wins is forbidden: the first registration survives.
203
+ expect(r.size).toBe(1);
204
+ });
205
+
206
+ it('refuses an invalid or reserved name', () => {
207
+ const r = new ServiceRegistry();
208
+ expect(() => r.register(fakeService('API'))).toThrow(ServiceRegistrationError);
209
+ expect(() => r.register(fakeService('list'))).toThrow(/reserved/);
210
+ });
211
+
212
+ it('override replaces in place and keeps position', () => {
213
+ const r = registryOf(fakeService('a'), fakeService('b'), fakeService('c'));
214
+ const replacement = fakeService('b', { addr: ':9999' });
215
+ r.override(replacement);
216
+ expect(r.names()).toEqual(['a', 'b', 'c']);
217
+ expect(r.lookup('b')!.addr!()).toBe(':9999');
218
+ });
219
+
220
+ it('override still refuses an invalid name', () => {
221
+ const r = new ServiceRegistry();
222
+ expect(() => r.override(fakeService('Bad'))).toThrow(ServiceRegistrationError);
223
+ });
224
+ });
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // The hierarchy
228
+ // ---------------------------------------------------------------------------
229
+
230
+ describe('resolve — the hierarchy', () => {
231
+ it('supervisor form selects every configured and enabled service', () => {
232
+ const r = registryOf(fakeService('api'), fakeService('socket'), fakeService('bus'));
233
+ const out = resolve(r, {
234
+ args: [],
235
+ configs: { api: { enabled: true }, socket: { enabled: false }, bus: { enabled: true } },
236
+ });
237
+ expect(out.error).toBeUndefined();
238
+ expect(out.explicit).toBe(false);
239
+ expect(out.selected).toEqual(['api', 'bus']);
240
+ });
241
+
242
+ it('skips a disabled service silently rather than failing', () => {
243
+ const r = registryOf(fakeService('api'), fakeService('socket'));
244
+ const out = resolve(r, {
245
+ args: [], configs: { api: { enabled: true }, socket: { enabled: false } },
246
+ });
247
+ expect(out.skipped).toEqual(['socket']);
248
+ expect(out.error).toBeUndefined();
249
+ });
250
+
251
+ it('ignores a service with no config block at all', () => {
252
+ const r = registryOf(fakeService('api'), fakeService('ghost'));
253
+ const out = resolve(r, { args: [], configs: { api: { enabled: true } } });
254
+ expect(out.selected).toEqual(['api']);
255
+ // Unconfigured is not the same as disabled: it is not even skipped.
256
+ expect(out.skipped).toEqual([]);
257
+ });
258
+
259
+ it('selector form selects exactly the named service', () => {
260
+ const r = registryOf(fakeService('api'), fakeService('socket'));
261
+ const out = resolve(r, { args: ['socket'], configs: enabled('api', 'socket') });
262
+ expect(out.selected).toEqual(['socket']);
263
+ expect(out.explicit).toBe(true);
264
+ });
265
+
266
+ it('selection preserves registration order, not argument order', () => {
267
+ const r = registryOf(fakeService('zeta'), fakeService('alpha'));
268
+ const out = resolve(r, { args: [], configs: enabled('zeta', 'alpha') });
269
+ expect(out.selected).toEqual(['zeta', 'alpha']);
270
+ });
271
+ });
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // The override rule
275
+ // ---------------------------------------------------------------------------
276
+
277
+ describe('resolve — the override rule', () => {
278
+ it('starts a disabled service when it is named explicitly', () => {
279
+ const r = registryOf(fakeService('api'));
280
+ const out = resolve(r, { args: ['api'], configs: { api: { enabled: false } } });
281
+ expect(out.error).toBeUndefined();
282
+ expect(out.selected).toEqual(['api']);
283
+ });
284
+
285
+ it('starts a service with no config block at all when named', () => {
286
+ // Enablement answers "does the supervisor start this by default";
287
+ // it is not an authorization decision, and an absent block is not
288
+ // a refusal under the selector form.
289
+ const r = registryOf(fakeService('api'));
290
+ const out = resolve(r, { args: ['api'], configs: {} });
291
+ expect(out.error).toBeUndefined();
292
+ expect(out.selected).toEqual(['api']);
293
+ });
294
+
295
+ it('the same service is refused under the supervisor form', () => {
296
+ // The contrast is the whole point of the rule: identical config,
297
+ // opposite answers, decided only by the explicit naming.
298
+ const r = registryOf(fakeService('api'));
299
+ const supervisor = resolve(r, { args: [], configs: { api: { enabled: false } } });
300
+ expect(supervisor.error?.exit_code).toBe(2);
301
+ const selector = resolve(r, { args: ['api'], configs: { api: { enabled: false } } });
302
+ expect(selector.error).toBeUndefined();
303
+ });
304
+
305
+ it('does NOT override the configuration gate', () => {
306
+ const r = registryOf(fakeService('api', { validate: () => 'addr: missing' }));
307
+ const out = resolve(r, { args: ['api'], configs: { api: { enabled: false } } });
308
+ expect(out.error?.code).toBe('USAGE');
309
+ expect(out.error?.exit_code).toBe(2);
310
+ expect(out.error?.message).toBe('service "api": addr: missing');
311
+ });
312
+
313
+ it('does NOT override the policy gate', () => {
314
+ const r = registryOf(fakeService('api', { cls: ['write-shared', 'ingress'] }));
315
+ const out = resolve(r, {
316
+ args: ['api'],
317
+ policy: { allow: () => ({ ok: false, reason: 'ingress denied' }) },
318
+ });
319
+ expect(out.error?.code).toBe('UNAUTHORIZED');
320
+ expect(out.error?.exit_code).toBe(5);
321
+ expect(out.error?.message).toContain('side_effect=write-shared, network=ingress');
322
+ expect(out.error?.message).toContain('ingress denied');
323
+ });
324
+
325
+ it('evaluates the gates in order: registration, config, policy', () => {
326
+ // A service that is both unregistered and would fail policy must
327
+ // answer NOT_FOUND, not UNAUTHORIZED — the operator's next step
328
+ // differs.
329
+ const r = registryOf(fakeService('api', { validate: () => 'broken' }));
330
+ const denyAll = { allow: () => ({ ok: false }) };
331
+
332
+ expect(resolve(r, { args: ['ghost'], policy: denyAll }).error?.code).toBe('NOT_FOUND');
333
+ // Registered but invalid config beats the policy gate.
334
+ expect(resolve(r, { args: ['api'], policy: denyAll }).error?.code).toBe('USAGE');
335
+ });
336
+
337
+ it('passes an unclassified service through the policy gate', () => {
338
+ const r = registryOf(fakeService('api'));
339
+ const out = resolve(r, { args: ['api'], policy: { allow: () => ({ ok: false }) } });
340
+ expect(out.error).toBeUndefined();
341
+ });
342
+
343
+ it('passes every service when no gate is wired', () => {
344
+ const r = registryOf(fakeService('api', { cls: ['destructive', 'ingress'] }));
345
+ expect(resolve(r, { args: ['api'] }).error).toBeUndefined();
346
+ });
347
+ });
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // Invalid selection
351
+ // ---------------------------------------------------------------------------
352
+
353
+ describe('resolve — invalid selection', () => {
354
+ it('refuses two or more positional arguments as USAGE/2', () => {
355
+ const r = registryOf(fakeService('api'), fakeService('socket'));
356
+ const out = resolve(r, { args: ['api', 'socket'], configs: enabled('api', 'socket') });
357
+ expect(out.error?.code).toBe('USAGE');
358
+ expect(out.error?.exit_code).toBe(2);
359
+ expect(out.error?.message).toBe('serve accepts at most one service name, got 2');
360
+ expect(out.selected).toEqual([]);
361
+ });
362
+
363
+ it('refuses an unknown service as NOT_FOUND/3, naming the known set', () => {
364
+ const r = registryOf(fakeService('api'), fakeService('socket'));
365
+ const out = resolve(r, { args: ['ghost'] });
366
+ expect(out.error?.code).toBe('NOT_FOUND');
367
+ expect(out.error?.exit_code).toBe(3);
368
+ expect(out.error?.message).toBe('unknown service "ghost"; known: api, socket');
369
+ });
370
+
371
+ it('suggests the nearest name on a near miss', () => {
372
+ const r = registryOf(fakeService('socket'));
373
+ expect(resolve(r, { args: ['sockat'] }).error?.suggested_fix).toBe('did you mean "socket"?');
374
+ });
375
+
376
+ it('suggests nothing when no name is close', () => {
377
+ const r = registryOf(fakeService('socket'));
378
+ expect(resolve(r, { args: ['zzzzzzzz'] }).error?.suggested_fix).toBeUndefined();
379
+ });
380
+
381
+ it('refuses a reserved word as a selection', () => {
382
+ // `list` can never be registered, so naming it can only ever be
383
+ // NOT_FOUND — which is what makes --list a flag rather than a child.
384
+ const r = registryOf(fakeService('api'));
385
+ expect(resolve(r, { args: ['list'] }).error?.code).toBe('NOT_FOUND');
386
+ });
387
+
388
+ it('refuses zero resolved services under the supervisor form', () => {
389
+ // Exiting 0 without listening is indistinguishable from a
390
+ // successful start to systemd or a container runtime.
391
+ const r = registryOf(fakeService('api'));
392
+ const out = resolve(r, { args: [], configs: { api: { enabled: false } } });
393
+ expect(out.error?.code).toBe('USAGE');
394
+ expect(out.error?.exit_code).toBe(2);
395
+ expect(out.error?.suggested_fix).toContain('services.<name>.enabled: true');
396
+ });
397
+
398
+ it('refuses an empty registry under the supervisor form', () => {
399
+ expect(resolve(new ServiceRegistry(), { args: [] }).error?.exit_code).toBe(2);
400
+ });
401
+ });
402
+
403
+ // ---------------------------------------------------------------------------
404
+ // Exit codes
405
+ // ---------------------------------------------------------------------------
406
+
407
+ describe('exit-code taxonomy', () => {
408
+ it('maps every outcome onto the contract table', () => {
409
+ // Literals, not the module's own constants: this is the table the
410
+ // sibling ports implement against.
411
+ const table: Array<[LifecycleOutcome, string, number]> = [
412
+ ['clean-stop', 'OK', 0],
413
+ ['invalid-selection', 'USAGE', 2],
414
+ ['config-invalid', 'USAGE', 2],
415
+ ['no-services', 'USAGE', 2],
416
+ ['unknown-service', 'NOT_FOUND', 3],
417
+ ['policy-denied', 'UNAUTHORIZED', 5],
418
+ ['start-failed', 'GENERIC', 1],
419
+ ['runtime-crash', 'GENERIC', 1],
420
+ ['shutdown-timeout', 'GENERIC', 1],
421
+ ];
422
+ for (const [outcome, code, exit] of table) {
423
+ expect(codeFor(outcome), outcome).toBe(code);
424
+ expect(exitCodeFor(outcome), outcome).toBe(exit);
425
+ }
426
+ });
427
+
428
+ it('treats a clean stop as success and everything else as failure', () => {
429
+ expect(isFailure('clean-stop')).toBe(false);
430
+ for (const o of ['invalid-selection', 'config-invalid', 'no-services',
431
+ 'unknown-service', 'policy-denied', 'start-failed', 'runtime-crash',
432
+ 'shutdown-timeout'] as LifecycleOutcome[]) {
433
+ expect(isFailure(o), o).toBe(true);
434
+ }
435
+ });
436
+
437
+ it('treats an unknown outcome as a failure, not a success', () => {
438
+ // A kind added without a table row must fail loudly rather than
439
+ // silently exit 0.
440
+ const rogue = 'invented-outcome' as LifecycleOutcome;
441
+ expect(exitCodeFor(rogue)).toBe(1);
442
+ expect(codeFor(rogue)).toBe('GENERIC');
443
+ });
444
+
445
+ it('worstOutcome keeps the first failure across a whole run', () => {
446
+ expect(worstOutcome([])).toBe('clean-stop');
447
+ expect(worstOutcome(['clean-stop'])).toBe('clean-stop');
448
+ // Severity, not magnitude: the first failure explains the rest,
449
+ // so a later one does not displace it.
450
+ expect(worstOutcome(['start-failed', 'shutdown-timeout'])).toBe('start-failed');
451
+ expect(worstOutcome(['clean-stop', 'policy-denied'])).toBe('policy-denied');
452
+ expect(worstOutcome(['runtime-crash', 'unknown-service'])).toBe('runtime-crash');
453
+ });
454
+ });
455
+
456
+ // ---------------------------------------------------------------------------
457
+ // Ordering
458
+ // ---------------------------------------------------------------------------
459
+
460
+ describe('startOrder', () => {
461
+ it('is registration order with no declarations', () => {
462
+ const r = registryOf(fakeService('a'), fakeService('b'), fakeService('c'));
463
+ expect(startOrder(r, ['a', 'b', 'c'])).toEqual(['a', 'b', 'c']);
464
+ });
465
+
466
+ it('puts a dependency before its dependent', () => {
467
+ const r = registryOf(fakeService('api', { dependsOn: ['db'] }), fakeService('db'));
468
+ expect(startOrder(r, ['api', 'db'])).toEqual(['db', 'api']);
469
+ });
470
+
471
+ it('ignores a dependency outside the selected set', () => {
472
+ // Under the selector form exactly one service runs, and its
473
+ // dependencies are the operator's business.
474
+ const r = registryOf(fakeService('api', { dependsOn: ['db'] }), fakeService('db'));
475
+ expect(startOrder(r, ['api'])).toEqual(['api']);
476
+ });
477
+
478
+ it('throws on a dependency cycle', () => {
479
+ const r = registryOf(
480
+ fakeService('a', { dependsOn: ['b'] }),
481
+ fakeService('b', { dependsOn: ['a'] }),
482
+ );
483
+ expect(() => startOrder(r, ['a', 'b'])).toThrow(/dependency cycle/);
484
+ });
485
+ });
486
+
487
+ // ---------------------------------------------------------------------------
488
+ // Topics
489
+ // ---------------------------------------------------------------------------
490
+
491
+ describe('lifecycle topics', () => {
492
+ it('produces exactly the six contract topic strings', () => {
493
+ expect(defaultTopics()).toEqual({
494
+ 'service.started': 'kit.serve.service.started',
495
+ 'service.ready_reported': 'kit.serve.service.ready_reported',
496
+ 'service.failed': 'kit.serve.service.failed',
497
+ 'service.stopped': 'kit.serve.service.stopped',
498
+ 'supervisor.ready_reported': 'kit.serve.supervisor.ready_reported',
499
+ 'supervisor.stopped': 'kit.serve.supervisor.stopped',
500
+ });
501
+ });
502
+
503
+ it('never emits a bare "ready" action', () => {
504
+ // A bare `ready` fails the past-tense validation in
505
+ // event-topics.md; Go subscribers reject it.
506
+ for (const t of Object.values(defaultTopics())) {
507
+ expect(t.endsWith('.ready'), t).toBe(false);
508
+ }
509
+ });
510
+
511
+ it('rebrands the prefix', () => {
512
+ expect(defaultTopics('acme.serve')['service.started'])
513
+ .toBe('acme.serve.service.started');
514
+ });
515
+ });
516
+
517
+ // ---------------------------------------------------------------------------
518
+ // Supervisor lifecycle
519
+ // ---------------------------------------------------------------------------
520
+
521
+ describe('Supervisor', () => {
522
+ it('starts, reports ready, and stops cleanly on a signal', async () => {
523
+ const api = fakeService('api', { addr: '127.0.0.1:8080' });
524
+ const pub = recorder();
525
+ const sup = new Supervisor(registryOf(api), { publisher: pub });
526
+
527
+ const res = await sup.run(abortAfter(10), ['api'], enabled('api'));
528
+
529
+ expect(res.outcome).toBe('clean-stop');
530
+ expect(res.exitCode).toBe(0);
531
+ expect(res.error).toBeUndefined();
532
+ expect(res.started).toEqual(['api']);
533
+ expect(res.ready).toEqual(['api']);
534
+ expect(api.stopCount).toBe(1);
535
+
536
+ const topics = pub.events.map((e) => e.topic);
537
+ expect(topics).toEqual([
538
+ 'kit.serve.service.started',
539
+ 'kit.serve.service.ready_reported',
540
+ 'kit.serve.supervisor.ready_reported',
541
+ 'kit.serve.service.stopped',
542
+ 'kit.serve.supervisor.stopped',
543
+ ]);
544
+ });
545
+
546
+ it('carries the resolved address on ready_reported and nowhere else', async () => {
547
+ const pub = recorder();
548
+ const sup = new Supervisor(registryOf(fakeService('api', { addr: '127.0.0.1:0' })), {
549
+ publisher: pub,
550
+ });
551
+ await sup.run(abortAfter(10), ['api'], enabled('api'));
552
+
553
+ for (const e of pub.events) {
554
+ if (e.topic === 'kit.serve.service.ready_reported') {
555
+ expect(e.payload.address).toBe('127.0.0.1:0');
556
+ } else {
557
+ expect(e.payload.address).toBeUndefined();
558
+ }
559
+ }
560
+ });
561
+
562
+ it('carries the service identifier in the payload, never in the topic', async () => {
563
+ const pub = recorder();
564
+ const sup = new Supervisor(registryOf(fakeService('api')), { publisher: pub });
565
+ await sup.run(abortAfter(10), ['api'], enabled('api'));
566
+
567
+ for (const e of pub.events) {
568
+ expect(e.topic).not.toContain('api');
569
+ if (e.topic.includes('.service.')) expect(e.payload.service).toBe('api');
570
+ }
571
+ });
572
+
573
+ it('reports the aggregate ready only when every service is ready', async () => {
574
+ const pub = recorder();
575
+ const sup = new Supervisor(registryOf(fakeService('a'), fakeService('b')), {
576
+ publisher: pub,
577
+ });
578
+ await sup.run(abortAfter(20), ['a', 'b'], enabled('a', 'b'));
579
+
580
+ const order = pub.events.map((e) => `${e.topic}:${e.payload.service ?? ''}`);
581
+ const aggregate = order.indexOf('kit.serve.supervisor.ready_reported:');
582
+ expect(aggregate).toBeGreaterThan(order.indexOf('kit.serve.service.ready_reported:a'));
583
+ expect(aggregate).toBeGreaterThan(order.indexOf('kit.serve.service.ready_reported:b'));
584
+ });
585
+
586
+ it('stops in the exact reverse of start order', async () => {
587
+ const a = fakeService('a');
588
+ const b = fakeService('b');
589
+ const c = fakeService('c');
590
+ stopSequence = 0;
591
+ const sup = new Supervisor(registryOf(a, b, c));
592
+ const res = await sup.run(abortAfter(20), ['a', 'b', 'c'], enabled('a', 'b', 'c'));
593
+
594
+ expect(res.started).toEqual(['a', 'b', 'c']);
595
+ // Lower sequence number = stopped earlier. c must be first.
596
+ expect(c.stopOrder[0]).toBeLessThan(b.stopOrder[0]!);
597
+ expect(b.stopOrder[0]).toBeLessThan(a.stopOrder[0]!);
598
+ });
599
+
600
+ it('treats a start failure as start-failed at exit 1', async () => {
601
+ const pub = recorder();
602
+ const sup = new Supervisor(
603
+ registryOf(fakeService('api', { failStartWith: 'bind: address in use' })),
604
+ { publisher: pub },
605
+ );
606
+ const res = await sup.run(abortAfter(50), ['api'], enabled('api'));
607
+
608
+ expect(res.outcome).toBe('start-failed');
609
+ expect(res.exitCode).toBe(1);
610
+ expect(res.error?.code).toBe('GENERIC');
611
+ expect(res.error?.message).toContain('api: bind: address in use');
612
+ expect(res.ready).toEqual([]);
613
+ expect(pub.events.some((e) =>
614
+ e.topic === 'kit.serve.service.failed' && e.payload.reason === 'start')).toBe(true);
615
+ });
616
+
617
+ it('treats a readiness timeout as a start failure', async () => {
618
+ const pub = recorder();
619
+ const sup = new Supervisor(registryOf(fakeService('api', { neverReady: true })));
620
+ const res = await sup.run(abortAfter(500), ['api'], {
621
+ api: { enabled: true, readyTimeoutMs: 15 },
622
+ });
623
+
624
+ expect(res.outcome).toBe('start-failed');
625
+ expect(res.exitCode).toBe(1);
626
+ expect(res.error?.message).toContain('not ready within 15ms');
627
+ void pub;
628
+ });
629
+
630
+ it('treats a service returning before ready as a start failure', async () => {
631
+ // Even a clean return is a failure here: it was asked to serve and
632
+ // it did not.
633
+ const sup = new Supervisor(registryOf(fakeService('api', { neverReady: true, returnAfterMs: 1 })));
634
+ const res = await sup.run(abortAfter(200), ['api'], enabled('api'));
635
+
636
+ expect(res.outcome).toBe('start-failed');
637
+ expect(res.error?.message).toContain('returned before reporting ready');
638
+ });
639
+
640
+ it('does not start a later service after an earlier one fails', async () => {
641
+ const second = fakeService('b');
642
+ const sup = new Supervisor(
643
+ registryOf(fakeService('a', { failStartWith: 'boom' }), second),
644
+ );
645
+ const res = await sup.run(abortAfter(100), ['a', 'b'], enabled('a', 'b'));
646
+
647
+ expect(res.outcome).toBe('start-failed');
648
+ expect(second.startCount).toBe(0);
649
+ });
650
+
651
+ it('brings everything down under fail-fast when one service crashes', async () => {
652
+ const survivor = fakeService('b');
653
+ const sup = new Supervisor(
654
+ registryOf(fakeService('a', { crashAfterMs: 'upstream gone' }), survivor),
655
+ { config: { failurePolicy: 'fail-fast' } },
656
+ );
657
+ const res = await sup.run(abortAfter(500), ['a', 'b'], enabled('a', 'b'));
658
+
659
+ expect(res.outcome).toBe('runtime-crash');
660
+ expect(res.exitCode).toBe(1);
661
+ expect(res.failed['a']).toBe('upstream gone');
662
+ expect(survivor.stopCount).toBe(1);
663
+ });
664
+
665
+ it('keeps the rest running under isolate until the last one stops', async () => {
666
+ const sup = new Supervisor(
667
+ registryOf(
668
+ fakeService('a', { crashAfterMs: 'gone' }),
669
+ fakeService('b', { returnAfterMs: 40 }),
670
+ ),
671
+ { config: { failurePolicy: 'isolate' } },
672
+ );
673
+ const res = await sup.run(abortAfter(1000), ['a', 'b'], enabled('a', 'b'));
674
+
675
+ // The process survived a's failure and ran until b returned, but
676
+ // the exit code still reflects the worst outcome of the whole run.
677
+ expect(res.failed['a']).toBe('gone');
678
+ expect(res.exitCode).toBe(1);
679
+ });
680
+
681
+ it('abandons a stop that exceeds its budget and moves on', async () => {
682
+ const later = fakeService('b');
683
+ const pub = recorder();
684
+ const sup = new Supervisor(
685
+ registryOf(fakeService('a', { hangInStop: true }), later),
686
+ { publisher: pub },
687
+ );
688
+ const res = await sup.run(abortAfter(10), ['a', 'b'], {
689
+ a: { enabled: true, stopTimeoutMs: 20 },
690
+ b: { enabled: true },
691
+ });
692
+
693
+ // b stops first (reverse order), then a's stop is abandoned rather
694
+ // than blocking the whole shutdown.
695
+ expect(later.stopCount).toBe(1);
696
+ expect(res.failed['a']).toContain('stop exceeded');
697
+ expect(pub.events.some((e) =>
698
+ e.topic === 'kit.serve.service.failed' && e.payload.reason === 'stop_timeout')).toBe(true);
699
+ });
700
+
701
+ it('reports a stop that rejects as a failure', async () => {
702
+ const sup = new Supervisor(registryOf(fakeService('api', { failStopWith: 'drain failed' })));
703
+ const res = await sup.run(abortAfter(10), ['api'], enabled('api'));
704
+ expect(res.failed['api']).toBe('drain failed');
705
+ expect(res.exitCode).toBe(1);
706
+ });
707
+
708
+ it('abandons the drain when the escalation signal fires', async () => {
709
+ const escalated = new AbortController();
710
+ escalated.abort();
711
+ const svc = fakeService('api');
712
+ const pub = recorder();
713
+ const sup = new Supervisor(registryOf(svc), {
714
+ escalate: escalated.signal, publisher: pub,
715
+ });
716
+ const res = await sup.run(abortAfter(10), ['api'], enabled('api'));
717
+
718
+ expect(svc.stopCount).toBe(0);
719
+ expect(res.exitCode).toBe(1);
720
+ expect(pub.events.some((e) =>
721
+ e.topic === 'kit.serve.service.failed' && e.payload.reason === 'escalated')).toBe(true);
722
+ });
723
+
724
+ it('refuses an empty selection rather than exiting 0', async () => {
725
+ const sup = new Supervisor(new ServiceRegistry());
726
+ const res = await sup.run(abortAfter(10), [], {});
727
+ expect(res.outcome).toBe('no-services');
728
+ expect(res.exitCode).toBe(2);
729
+ });
730
+
731
+ it('emits the log counterpart when no bus is wired', async () => {
732
+ // A tool with no bus still produces an operator-legible trace, with
733
+ // the identifier and address as structured fields.
734
+ const log = { info: vi.fn(), error: vi.fn() };
735
+ const sup = new Supervisor(registryOf(fakeService('api', { addr: ':8080' })), { logger: log });
736
+ await sup.run(abortAfter(10), ['api'], enabled('api'));
737
+
738
+ const readyCall = log.info.mock.calls.find((c) => c[0] === 'serve: ready_reported');
739
+ expect(readyCall).toBeDefined();
740
+ expect(readyCall).toContain('service');
741
+ expect(readyCall).toContain('api');
742
+ expect(readyCall).toContain('address');
743
+ expect(readyCall).toContain(':8080');
744
+ });
745
+
746
+ it('logs a failure at error level, not info', async () => {
747
+ const log = { info: vi.fn(), error: vi.fn() };
748
+ const sup = new Supervisor(registryOf(fakeService('api', { failStartWith: 'nope' })), {
749
+ logger: log,
750
+ });
751
+ await sup.run(abortAfter(50), ['api'], enabled('api'));
752
+
753
+ expect(log.error).toHaveBeenCalled();
754
+ expect(log.error.mock.calls[0]![0]).toBe('serve: failed');
755
+ expect(log.info.mock.calls.every((c) => c[0] !== 'serve: failed')).toBe(true);
756
+ });
757
+
758
+ it('survives a publisher that throws', async () => {
759
+ // An event sink is observability, not correctness.
760
+ const sup = new Supervisor(registryOf(fakeService('api')), {
761
+ publisher: { publish() { throw new Error('bus down'); } },
762
+ });
763
+ const res = await sup.run(abortAfter(10), ['api'], enabled('api'));
764
+ expect(res.outcome).toBe('clean-stop');
765
+ });
766
+
767
+ it('runs twice on one registry, each observing only its own signal', async () => {
768
+ // A run is over when the supervisor returns; the registry it ran
769
+ // on is not consumed.
770
+ const reg = registryOf(fakeService('api'));
771
+ const sup = new Supervisor(reg);
772
+ const first = await sup.run(abortAfter(10), ['api'], enabled('api'));
773
+ const second = await sup.run(abortAfter(10), ['api'], enabled('api'));
774
+
775
+ expect(first.outcome).toBe('clean-stop');
776
+ expect(second.outcome).toBe('clean-stop');
777
+ expect(second.ready).toEqual(['api']);
778
+ });
779
+
780
+ it('returns immediately when handed an already-aborted signal', async () => {
781
+ const ac = new AbortController();
782
+ ac.abort();
783
+ const sup = new Supervisor(registryOf(fakeService('api')));
784
+ const res = await sup.run(ac.signal, ['api'], enabled('api'));
785
+ expect(res.outcome).toBe('clean-stop');
786
+ });
787
+ });
788
+
789
+ // ---------------------------------------------------------------------------
790
+ // Defaults
791
+ // ---------------------------------------------------------------------------
792
+
793
+ describe('configuration defaults', () => {
794
+ it('matches the contract table', () => {
795
+ expect(DEFAULT_READY_TIMEOUT_MS).toBe(30_000);
796
+ expect(DEFAULT_STOP_TIMEOUT_MS).toBe(30_000);
797
+ expect(DEFAULT_SHUTDOWN_TIMEOUT_MS).toBe(60_000);
798
+ expect(DEFAULT_FAILURE_POLICY).toBe('fail-fast');
799
+ });
800
+
801
+ it('treats enabled as false unless it is explicitly true', () => {
802
+ // An unrequested open port is the risk this default guards against,
803
+ // so anything short of an explicit true is disabled.
804
+ const r = registryOf(fakeService('api'));
805
+ for (const cfg of [{}, { enabled: false }, { enabled: undefined }] as ServiceConfig[]) {
806
+ expect(resolve(r, { args: [], configs: { api: cfg } }).selected).toEqual([]);
807
+ }
808
+ expect(resolve(r, { args: [], configs: { api: { enabled: true } } }).selected).toEqual(['api']);
809
+ });
810
+ });
811
+
812
+ // ---------------------------------------------------------------------------
813
+ // Signals
814
+ // ---------------------------------------------------------------------------
815
+
816
+ describe('signalController', () => {
817
+ // The listeners are driven with process.emit rather than a real
818
+ // process.kill: delivering an actual SIGINT/SIGTERM to the test
819
+ // process kills the vitest worker. emit dispatches to exactly the
820
+ // listeners signalController registered with process.on, so the
821
+ // registration path under test is the real one.
822
+ const raise = (sig: NodeJS.Signals): void => { process.emit(sig); };
823
+
824
+ it('aborts on the first signal and escalates on the second', () => {
825
+ const c = signalController();
826
+ try {
827
+ expect(c.signal.aborted).toBe(false);
828
+ expect(c.escalate.aborted).toBe(false);
829
+
830
+ raise('SIGTERM');
831
+ expect(c.signal.aborted).toBe(true);
832
+ // The first signal begins a graceful drain; it does not escalate.
833
+ expect(c.escalate.aborted).toBe(false);
834
+
835
+ // A second signal of *either* kind aborts the drain, so an
836
+ // operator can escalate without reaching for SIGKILL.
837
+ raise('SIGINT');
838
+ expect(c.escalate.aborted).toBe(true);
839
+ } finally {
840
+ c.stop();
841
+ }
842
+ });
843
+
844
+ it('escalates on a repeat of the same signal too', () => {
845
+ const c = signalController();
846
+ try {
847
+ raise('SIGINT');
848
+ expect(c.escalate.aborted).toBe(false);
849
+ raise('SIGINT');
850
+ expect(c.escalate.aborted).toBe(true);
851
+ } finally {
852
+ c.stop();
853
+ }
854
+ });
855
+
856
+ it('ignores signals after stop', () => {
857
+ const c = signalController();
858
+ c.stop();
859
+ raise('SIGTERM');
860
+ expect(c.signal.aborted).toBe(false);
861
+ });
862
+
863
+ it('removes its process listeners on stop', () => {
864
+ const before = process.listenerCount('SIGTERM');
865
+ const c = signalController();
866
+ expect(process.listenerCount('SIGTERM')).toBe(before + 1);
867
+ c.stop();
868
+ expect(process.listenerCount('SIGTERM')).toBe(before);
869
+ c.stop(); // idempotent
870
+ expect(process.listenerCount('SIGTERM')).toBe(before);
871
+ });
872
+ });
873
+
874
+ // ---------------------------------------------------------------------------
875
+ // Keeping the process alive
876
+ // ---------------------------------------------------------------------------
877
+
878
+ describe('LoopKeepAlive', () => {
879
+ // Neither a process signal listener nor an AbortSignal listener refs
880
+ // the Node event loop. Without a referenced handle a supervisor whose
881
+ // services are all parked on their abort signal lets the process exit
882
+ // 0 the moment `run` yields — a process that exits 0 without
883
+ // listening, which is indistinguishable from a successful start to
884
+ // systemd or a container runtime.
885
+ it('holds a referenced handle only between hold and release', () => {
886
+ const k = new LoopKeepAlive();
887
+ expect(k.held).toBe(false);
888
+ k.hold();
889
+ expect(k.held).toBe(true);
890
+ k.hold(); // idempotent
891
+ expect(k.held).toBe(true);
892
+ k.release();
893
+ expect(k.held).toBe(false);
894
+ k.release(); // idempotent
895
+ expect(k.held).toBe(false);
896
+ });
897
+ });
898
+
899
+ describe('serving in a real process', () => {
900
+ // The unit tests above all drive the supervisor with an abort signal
901
+ // that fires on a timer, so they would pass even if nothing held the
902
+ // event loop open. Only a subprocess proves the process actually
903
+ // stays up: it is the difference between "the run resolved" and "the
904
+ // tool served".
905
+ // Inside the package rather than the temp dir: the harness
906
+ // `require`s commander, which only resolves from a path under
907
+ // node_modules' reach.
908
+ const entry = path.join(__dirname, '..', `.serve-e2e-${process.pid}.cjs`);
909
+
910
+ beforeAll(() => {
911
+ const src = path.join(__dirname, 'serve.ts');
912
+ const built = execFileSync(
913
+ path.join(__dirname, '..', 'node_modules', '.bin', 'esbuild'),
914
+ [src, '--bundle', '--platform=node', '--format=cjs', '--log-level=error'],
915
+ { encoding: 'utf8' },
916
+ );
917
+ writeFileSync(entry, `${built}
918
+ const registry = new ServiceRegistry();
919
+ registry.register({
920
+ name: 'api',
921
+ async start(signal, ready) {
922
+ ready();
923
+ await new Promise((r) => signal.addEventListener('abort', () => r(), { once: true }));
924
+ },
925
+ ready: () => true,
926
+ async stop() {},
927
+ });
928
+ const { Command } = require('commander');
929
+ const program = new Command('tool');
930
+ registerServe(program, { registry, configs: { api: { enabled: true } } });
931
+ // No exitOverride and no catch that rewrites the code: registerServe
932
+ // sets process.exitCode itself, and swallowing that into a blanket 1
933
+ // is exactly the masking this test exists to catch.
934
+ program.parseAsync(process.argv.slice(2), { from: 'user' });
935
+ `);
936
+ });
937
+
938
+ afterAll(() => { rmSync(entry, { force: true }); });
939
+
940
+ it('stays alive while serving and exits 0 on SIGTERM', async () => {
941
+ const child = spawn(process.execPath, [entry, 'serve', 'api'], { stdio: 'ignore' });
942
+ try {
943
+ await sleep(600);
944
+ // Still running: the supervisor held the loop open rather than
945
+ // letting node fall off the end of the script.
946
+ expect(child.exitCode).toBeNull();
947
+
948
+ child.kill('SIGTERM');
949
+ const code = await new Promise<number | null>((r) => child.on('exit', r));
950
+ // A signal-initiated stop is a clean stop. Answering SIGTERM
951
+ // non-zero makes every rolling restart look like a crash.
952
+ expect(code).toBe(0);
953
+ } finally {
954
+ if (child.exitCode === null) child.kill('SIGKILL');
955
+ }
956
+ }, 20_000);
957
+
958
+ it('exits 2 on two service operands', async () => {
959
+ const code = await runToCompletion(entry, ['serve', 'api', 'socket']);
960
+ expect(code).toBe(2);
961
+ }, 20_000);
962
+
963
+ it('exits 3 on an unknown service', async () => {
964
+ const code = await runToCompletion(entry, ['serve', 'ghost']);
965
+ expect(code).toBe(3);
966
+ }, 20_000);
967
+ });
968
+
969
+ /** Runs the built entry to completion and resolves its exit code. */
970
+ function runToCompletion(entry: string, argv: string[]): Promise<number | null> {
971
+ const child = spawn(process.execPath, [entry, ...argv], { stdio: 'ignore' });
972
+ return new Promise((r) => child.on('exit', r));
973
+ }
974
+
975
+ // ---------------------------------------------------------------------------
976
+ // Command wiring
977
+ // ---------------------------------------------------------------------------
978
+
979
+ describe('registerServe', () => {
980
+ /** Builds a program whose serve run reports its exit code to the test. */
981
+ function programWith(
982
+ registry: ServiceRegistry,
983
+ configs: Record<string, ServiceConfig>,
984
+ extra: Partial<Parameters<typeof registerServe>[1]> = {},
985
+ ): { program: Command; exits: Array<{ code: number; message?: string }>; out: string[] } {
986
+ const exits: Array<{ code: number; message?: string }> = [];
987
+ const out: string[] = [];
988
+ const program = new Command('tool').exitOverride();
989
+ registerServe(program, {
990
+ registry,
991
+ configs,
992
+ stdout: { write: (s: string) => { out.push(s); return true; } },
993
+ onExit: (code, error) => exits.push({ code, message: error?.message }),
994
+ ...extra,
995
+ });
996
+ return { program, exits, out };
997
+ }
998
+
999
+ it('mounts serve with an optional service operand', () => {
1000
+ const { program } = programWith(registryOf(fakeService('api')), {});
1001
+ const serve = program.commands.find((c) => c.name() === 'serve');
1002
+ expect(serve).toBeDefined();
1003
+ expect(serve!.description()).toBe('Run configured services under one lifecycle');
1004
+ });
1005
+
1006
+ it('does not mount a `list` child', () => {
1007
+ // `list` is reserved selector vocabulary; the inspection form is a
1008
+ // flag so it cannot be confused with the selector form.
1009
+ const { program } = programWith(registryOf(fakeService('api')), {});
1010
+ const serve = program.commands.find((c) => c.name() === 'serve')!;
1011
+ expect(serve.commands.map((c) => c.name())).not.toContain('list');
1012
+ expect(serve.options.some((o) => o.long === '--list')).toBe(true);
1013
+ });
1014
+
1015
+ it('--list prints every service in registration order', async () => {
1016
+ const { program, out } = programWith(
1017
+ registryOf(fakeService('zeta'), fakeService('alpha')),
1018
+ { zeta: { enabled: true } },
1019
+ );
1020
+ await program.parseAsync(['serve', '--list'], { from: 'user' });
1021
+
1022
+ const text = out.join('');
1023
+ expect(text).toContain('SERVICE');
1024
+ expect(text.indexOf('zeta')).toBeLessThan(text.indexOf('alpha'));
1025
+ expect(text).toMatch(/zeta\s+true\s+true/);
1026
+ // alpha has no config block: not configured, not enabled.
1027
+ expect(text).toMatch(/alpha\s+false\s+false/);
1028
+ });
1029
+
1030
+ it('exits 2 on two or more service operands', async () => {
1031
+ // Commander's own excess-argument refusal exits 1; the contract
1032
+ // says 2, so the arity check is owned here.
1033
+ const { program, exits } = programWith(
1034
+ registryOf(fakeService('api'), fakeService('socket')),
1035
+ enabled('api', 'socket'),
1036
+ );
1037
+ await program.parseAsync(['serve', 'api', 'socket'], { from: 'user' });
1038
+
1039
+ expect(exits).toEqual([{ code: 2, message: 'serve accepts at most one service name, got 2' }]);
1040
+ });
1041
+
1042
+ it('exits 3 on an unknown service', async () => {
1043
+ const { program, exits } = programWith(registryOf(fakeService('api')), enabled('api'));
1044
+ await program.parseAsync(['serve', 'ghost'], { from: 'user' });
1045
+
1046
+ expect(exits[0]!.code).toBe(3);
1047
+ expect(exits[0]!.message).toContain('unknown service "ghost"');
1048
+ });
1049
+
1050
+ it('exits 5 when the policy gate denies the named service', async () => {
1051
+ const { program, exits } = programWith(
1052
+ registryOf(fakeService('api', { cls: ['destructive', 'ingress'] })),
1053
+ enabled('api'),
1054
+ { policy: { allow: () => ({ ok: false, reason: 'blocked' }) } },
1055
+ );
1056
+ await program.parseAsync(['serve', 'api'], { from: 'user' });
1057
+ expect(exits[0]!.code).toBe(5);
1058
+ });
1059
+
1060
+ it('exits 2 when the supervisor form resolves to nothing', async () => {
1061
+ const { program, exits } = programWith(
1062
+ registryOf(fakeService('api')), { api: { enabled: false } },
1063
+ );
1064
+ await program.parseAsync(['serve'], { from: 'user' });
1065
+ expect(exits[0]!.code).toBe(2);
1066
+ });
1067
+
1068
+ it('exits 0 for a clean signal-initiated stop', async () => {
1069
+ const { program, exits } = programWith(
1070
+ registryOf(fakeService('api', { returnAfterMs: 5 })), enabled('api'),
1071
+ );
1072
+ await program.parseAsync(['serve', 'api'], { from: 'user' });
1073
+ expect(exits).toEqual([{ code: 0, message: undefined }]);
1074
+ });
1075
+
1076
+ it('runs a disabled service through the selector form and exits 0', async () => {
1077
+ // The override rule, end to end through the command surface.
1078
+ const svc = fakeService('api', { returnAfterMs: 5 });
1079
+ const { program, exits } = programWith(registryOf(svc), { api: { enabled: false } });
1080
+ await program.parseAsync(['serve', 'api'], { from: 'user' });
1081
+
1082
+ expect(svc.startCount).toBe(1);
1083
+ expect(exits[0]!.code).toBe(0);
1084
+ });
1085
+
1086
+ it('exits 1 when the selected service fails to start', async () => {
1087
+ const { program, exits } = programWith(
1088
+ registryOf(fakeService('api', { failStartWith: 'bind refused' })), enabled('api'),
1089
+ );
1090
+ await program.parseAsync(['serve', 'api'], { from: 'user' });
1091
+
1092
+ expect(exits[0]!.code).toBe(1);
1093
+ expect(exits[0]!.message).toContain('bind refused');
1094
+ });
1095
+
1096
+ // -- --enable / --disable -------------------------------------------
1097
+
1098
+ it('--enable is repeatable and makes an unconfigured service configured and enabled', async () => {
1099
+ // Neither service has a config block: the flag is what configures
1100
+ // each one, and naming both starts both.
1101
+ const a = fakeService('alpha', { returnAfterMs: 5 });
1102
+ const b = fakeService('beta', { returnAfterMs: 5 });
1103
+ const { program, exits } = programWith(registryOf(a, b), {});
1104
+ await program.parseAsync(
1105
+ ['serve', '--enable', 'alpha', '--enable', 'beta'], { from: 'user' },
1106
+ );
1107
+
1108
+ expect(a.startCount).toBe(1);
1109
+ expect(b.startCount).toBe(1);
1110
+ expect(exits).toEqual([{ code: 0, message: undefined }]);
1111
+ });
1112
+
1113
+ it('--disable skips an enabled service silently under the supervisor form', async () => {
1114
+ const on = fakeService('on', { returnAfterMs: 5 });
1115
+ const off = fakeService('off', { returnAfterMs: 5 });
1116
+ const { program, exits } = programWith(registryOf(on, off), enabled('on', 'off'));
1117
+ await program.parseAsync(['serve', '--disable', 'off'], { from: 'user' });
1118
+
1119
+ expect(on.startCount).toBe(1);
1120
+ expect(off.startCount).toBe(0);
1121
+ expect(exits).toEqual([{ code: 0, message: undefined }]);
1122
+ });
1123
+
1124
+ it('--disable on every enabled service leaves nothing to run and exits 2', async () => {
1125
+ // returnAfterMs keeps a regression from hanging the suite: a service
1126
+ // the flag failed to disable would otherwise wait for a signal.
1127
+ const { program, exits } = programWith(
1128
+ registryOf(fakeService('api', { returnAfterMs: 5 })), enabled('api'),
1129
+ );
1130
+ await program.parseAsync(['serve', '--disable', 'api'], { from: 'user' });
1131
+ expect(exits[0]!.code).toBe(2);
1132
+ });
1133
+
1134
+ it.each([['--enable'], ['--disable']])(
1135
+ 'refuses %s under the selector form with USAGE exit 2', async (flag) => {
1136
+ const svc = fakeService('api', { returnAfterMs: 5 });
1137
+ const { program, exits } = programWith(registryOf(svc), enabled('api'));
1138
+ await program.parseAsync(['serve', 'api', flag, 'api'], { from: 'user' });
1139
+
1140
+ expect(svc.startCount).toBe(0);
1141
+ expect(exits).toEqual([{
1142
+ code: 2,
1143
+ message: '--enable/--disable apply to the supervisor form; drop the service name or drop the flags',
1144
+ }]);
1145
+ },
1146
+ );
1147
+
1148
+ it('does not let the flags leak into the caller\'s configs', async () => {
1149
+ const configs: Record<string, ServiceConfig> = { api: { enabled: true } };
1150
+ const { program } = programWith(registryOf(fakeService('api', { returnAfterMs: 5 })), configs);
1151
+ await program.parseAsync(['serve', '--disable', 'api'], { from: 'user' });
1152
+ expect(configs.api!.enabled).toBe(true);
1153
+ });
1154
+
1155
+ // -- timeout flags ----------------------------------------------------
1156
+
1157
+ it('--ready-timeout bounds start for every resolved service', async () => {
1158
+ // Without the flag the default 30s budget would outlive the test;
1159
+ // the flag is what turns a never-ready service into a start failure.
1160
+ const { program, exits } = programWith(
1161
+ registryOf(fakeService('api', { neverReady: true })), enabled('api'),
1162
+ );
1163
+ await program.parseAsync(['serve', '--ready-timeout', '15ms'], { from: 'user' });
1164
+
1165
+ expect(exits[0]!.code).toBe(1);
1166
+ expect(exits[0]!.message).toContain('ready');
1167
+ });
1168
+
1169
+ it('--shutdown-timeout bounds the whole stop', async () => {
1170
+ const { program, exits } = programWith(
1171
+ registryOf(fakeService('api', { hangInStop: true, returnAfterMs: 1 })), enabled('api'),
1172
+ );
1173
+ await program.parseAsync(
1174
+ ['serve', 'api', '--stop-timeout', '10ms', '--shutdown-timeout', '15ms'], { from: 'user' },
1175
+ );
1176
+ expect(exits[0]!.code).toBe(1);
1177
+ });
1178
+
1179
+ it('refuses an unparseable duration as USAGE exit 2', async () => {
1180
+ const svc = fakeService('api', { returnAfterMs: 5 });
1181
+ const { program, exits } = programWith(registryOf(svc), enabled('api'));
1182
+ await program.parseAsync(['serve', '--ready-timeout', '30x'], { from: 'user' });
1183
+
1184
+ expect(svc.startCount).toBe(0);
1185
+ expect(exits[0]!.code).toBe(2);
1186
+ expect(exits[0]!.message).toContain('--ready-timeout');
1187
+ });
1188
+
1189
+ it('leaves no signal listeners behind after a run', async () => {
1190
+ const before = process.listenerCount('SIGTERM');
1191
+ const { program } = programWith(
1192
+ registryOf(fakeService('api', { returnAfterMs: 5 })), enabled('api'),
1193
+ );
1194
+ await program.parseAsync(['serve', 'api'], { from: 'user' });
1195
+ expect(process.listenerCount('SIGTERM')).toBe(before);
1196
+ });
1197
+ });
1198
+
1199
+ // ---------------------------------------------------------------------------
1200
+ // Flag overrides
1201
+ // ---------------------------------------------------------------------------
1202
+
1203
+ describe('applyEnableDisable', () => {
1204
+ it('enable makes an unconfigured service configured and enabled', () => {
1205
+ expect(applyEnableDisable({}, ['api'], [])).toEqual({ api: { enabled: true } });
1206
+ });
1207
+
1208
+ it('disable clears enablement on a configured service and keeps its budgets', () => {
1209
+ const out = applyEnableDisable({ api: { enabled: true, readyTimeoutMs: 5 } }, [], ['api']);
1210
+ expect(out).toEqual({ api: { enabled: false, readyTimeoutMs: 5 } });
1211
+ });
1212
+
1213
+ it('disable on an unconfigured service is a no-op', () => {
1214
+ expect(applyEnableDisable({}, [], ['ghost'])).toEqual({});
1215
+ });
1216
+
1217
+ it('enable wins over disable for the same name', () => {
1218
+ expect(applyEnableDisable({}, ['api'], ['api'])).toEqual({ api: { enabled: true } });
1219
+ });
1220
+
1221
+ it('returns a new map rather than mutating the input', () => {
1222
+ const input: Record<string, ServiceConfig> = { api: { enabled: true } };
1223
+ const out = applyEnableDisable(input, [], ['api']);
1224
+ expect(input.api!.enabled).toBe(true);
1225
+ expect(out).not.toBe(input);
1226
+ });
1227
+ });
1228
+
1229
+ describe('applyTimeoutOverrides', () => {
1230
+ it('applies one budget to every resolved service', () => {
1231
+ const out = applyTimeoutOverrides(
1232
+ { a: { enabled: true }, b: { enabled: false, stopTimeoutMs: 1 } }, 10, 20,
1233
+ );
1234
+ expect(out).toEqual({
1235
+ a: { enabled: true, readyTimeoutMs: 10, stopTimeoutMs: 20 },
1236
+ b: { enabled: false, readyTimeoutMs: 10, stopTimeoutMs: 20 },
1237
+ });
1238
+ });
1239
+
1240
+ it('leaves the map alone when neither flag is set', () => {
1241
+ const out = applyTimeoutOverrides({ a: { enabled: true, readyTimeoutMs: 7 } });
1242
+ expect(out).toEqual({ a: { enabled: true, readyTimeoutMs: 7 } });
1243
+ });
1244
+ });
1245
+
1246
+ describe('parseDurationMs', () => {
1247
+ it.each([
1248
+ ['30s', 30_000], ['500ms', 500], ['1m30s', 90_000], ['1h', 3_600_000],
1249
+ ['1.5s', 1_500], ['2', 2_000],
1250
+ ])('parses %s', (raw, ms) => {
1251
+ expect(parseDurationMs(raw)).toBe(ms);
1252
+ });
1253
+
1254
+ it.each([[''], ['30x'], ['s'], ['1m 30s'], ['abc']])('rejects %j', (raw) => {
1255
+ expect(parseDurationMs(raw)).toBeNull();
1256
+ });
1257
+ });