File size: 23,492 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// Node daemon tests cover node daemon command runtime behavior and errors.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { GatewayServiceRuntime } from "../../daemon/service-runtime.js";
import type { GatewayServiceCommandConfig } from "../../daemon/service-types.js";
import { withEnvAsync } from "../../test-utils/env.js";
import {
  runNodeDaemonInstall,
  runNodeDaemonRestart,
  runNodeDaemonStart,
  runNodeDaemonStatus,
  runNodeDaemonStop,
  runNodeDaemonUninstall,
} from "./daemon.js";

const TLS_FINGERPRINT = "ab".repeat(32);

const mocks = vi.hoisted(() => {
  const service = {
    label: "Node service",
    loadedText: "loaded",
    notLoadedText: "not loaded",
    stage: vi.fn(),
    install: vi.fn(),
    uninstall: vi.fn(),
    stop: vi.fn(),
    restart: vi.fn(),
    isLoaded: vi.fn(async () => true),
    readCommand: vi.fn<() => Promise<GatewayServiceCommandConfig | null>>(async () => null),
    readRuntime: vi.fn<() => Promise<GatewayServiceRuntime>>(async () => ({ status: "running" })),
  };
  return {
    runtime: {
      log: vi.fn<(line: string) => void>(),
      error: vi.fn<(line: string) => void>(),
      writeJson: vi.fn(),
      exit: vi.fn(),
    },
    service,
    buildNodeInstallPlan: vi.fn(async () => ({
      programArguments: ["node", "node-host"],
      environment: {},
      environmentValueSources: {},
    })),
    loadNodeHostConfig: vi.fn(),
    isSystemdUserServiceAvailable: vi.fn(async () => true),
    resolveSystemdUserServiceAccount: vi.fn(() => "pi"),
    readSystemdUserLingerStatus: vi.fn(
      async (): Promise<{ user: string; linger: "yes" | "no" }> => ({
        user: "pi",
        linger: "no",
      }),
    ),
    runServiceRestart: vi.fn(),
    runServiceStart: vi.fn(),
    runServiceStop: vi.fn(),
    runServiceUninstall: vi.fn(),
  };
});

vi.mock("../../runtime.js", () => ({
  defaultRuntime: mocks.runtime,
}));

vi.mock("../../daemon/node-service.js", () => ({
  resolveNodeService: () => mocks.service,
}));

vi.mock("../../commands/node-daemon-install-helpers.js", () => ({
  buildNodeInstallPlan: mocks.buildNodeInstallPlan,
}));

vi.mock("../../node-host/config.js", () => ({
  loadNodeHostConfig: mocks.loadNodeHostConfig,
}));

vi.mock("../daemon-cli/lifecycle-core.js", () => ({
  runServiceRestart: mocks.runServiceRestart,
  runServiceStart: mocks.runServiceStart,
  runServiceStop: mocks.runServiceStop,
  runServiceUninstall: mocks.runServiceUninstall,
}));

vi.mock("../../daemon/runtime-hints.js", () => ({
  buildPlatformRuntimeLogHints: () => [
    "Logs: node service log",
    "Restart attempts: node restart log",
  ],
  buildPlatformServiceStartHints: () => ["openclaw node install", "openclaw node start"],
}));

vi.mock("../../daemon/systemd.js", async () => {
  const actual =
    await vi.importActual<typeof import("../../daemon/systemd.js")>("../../daemon/systemd.js");
  return {
    ...actual,
    isSystemdUserServiceAvailable: mocks.isSystemdUserServiceAvailable,
    resolveSystemdUserServiceAccount: mocks.resolveSystemdUserServiceAccount,
    readSystemdUserLingerStatus: mocks.readSystemdUserLingerStatus,
  };
});

vi.mock("../../../packages/terminal-core/src/theme.js", async () => {
  const actual = await vi.importActual<
    typeof import("../../../packages/terminal-core/src/theme.js")
  >("../../../packages/terminal-core/src/theme.js");
  return {
    ...actual,
    colorize: (_rich: boolean, _theme: unknown, text: string) => text,
  };
});

vi.mock("../daemon-cli/shared.js", async () => {
  const actual =
    await vi.importActual<typeof import("../daemon-cli/shared.js")>("../daemon-cli/shared.js");
  return {
    ...actual,
    createCliStatusTextStyles: () => ({
      rich: false,
      label: (text: string) => text,
      accent: (text: string) => text,
      infoText: (text: string) => text,
      okText: (text: string) => text,
      warnText: (text: string) => text,
      errorText: (text: string) => text,
    }),
    formatRuntimeStatus: (runtime: GatewayServiceRuntime | undefined) => runtime?.status ?? "",
    resolveRuntimeStatusColor: () => "",
  };
});

function useLinuxPlatform(): void {
  vi.spyOn(process, "platform", "get").mockReturnValue("linux");
}

afterEach(() => {
  vi.restoreAllMocks();
  vi.unstubAllEnvs();
});

describe("runNodeDaemonInstall", () => {
  beforeEach(() => {
    mocks.runtime.log.mockClear();
    mocks.runtime.error.mockClear();
    mocks.runtime.writeJson.mockClear();
    mocks.runtime.exit.mockClear();
    vi.stubEnv("OPENCLAW_NIX_MODE", undefined);
    mocks.service.install.mockReset().mockResolvedValue(undefined);
    mocks.service.isLoaded.mockReset().mockResolvedValue(false);
    mocks.buildNodeInstallPlan.mockReset().mockResolvedValue({
      programArguments: ["node", "node-host"],
      environment: {},
      environmentValueSources: {},
    });
    mocks.loadNodeHostConfig.mockReset().mockResolvedValue({
      gateway: {
        host: "saved-gateway.local",
        port: 18789,
        contextPath: "/saved",
        tls: true,
        tlsFingerprint: TLS_FINGERPRINT,
      },
    });
    mocks.isSystemdUserServiceAvailable.mockReset().mockResolvedValue(true);
    mocks.resolveSystemdUserServiceAccount.mockReset().mockReturnValue("pi");
    mocks.readSystemdUserLingerStatus.mockReset().mockResolvedValue({
      user: "pi",
      linger: "no",
    });
  });

  it.each([
    ["host", { host: "new-gateway.local" }],
    ["port", { port: 19_001 }],
  ])("does not inherit saved TLS when %s explicitly retargets the gateway", async (_name, opts) => {
    await runNodeDaemonInstall({ ...opts, force: true });

    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
      expect.objectContaining({
        contextPath: undefined,
        tls: false,
        tlsFingerprint: undefined,
      }),
    );
  });

  it("inherits saved TLS and forwards explicit command restrictions to the install plan", async () => {
    await runNodeDaemonInstall({ force: true, commands: ["fixture.list", "fixture.read"] });

    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
      expect.objectContaining({
        host: "saved-gateway.local",
        port: 18789,
        contextPath: "/saved",
        tls: true,
        tlsFingerprint: TLS_FINGERPRINT,
        commands: ["fixture.list", "fixture.read"],
      }),
    );
  });

  it("forwards a full-surface reset when replacing a restricted service", async () => {
    mocks.loadNodeHostConfig.mockResolvedValue({
      gateway: { host: "saved-gateway.local", port: 18789 },
      commands: ["fixture.read"],
    });
    await runNodeDaemonInstall({ force: true, allCommands: true });
    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
      expect.objectContaining({ allCommands: true, commands: undefined }),
    );
    expect(mocks.service.install).toHaveBeenCalledOnce();
  });

  it.each([
    ["host", { host: "saved-gateway.local" }],
    ["port", { port: 18_789 }],
  ])("keeps saved TLS when explicit %s resolves to the saved endpoint", async (_name, opts) => {
    await runNodeDaemonInstall({ ...opts, force: true });

    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
      expect.objectContaining({
        contextPath: "/saved",
        tls: true,
        tlsFingerprint: TLS_FINGERPRINT,
      }),
    );
  });

  it("installs an explicitly plaintext node for a saved TLS gateway", async () => {
    await runNodeDaemonInstall({ force: true, tls: false });

    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
      expect.objectContaining({
        host: "saved-gateway.local",
        port: 18789,
        contextPath: "/saved",
        tls: false,
        tlsFingerprint: undefined,
      }),
    );
  });

  it("rejects a TLS fingerprint when installing an explicitly plaintext node", async () => {
    await runNodeDaemonInstall({ force: true, tls: false, tlsFingerprint: TLS_FINGERPRINT });

    expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
    expect(mocks.runtime.error).toHaveBeenCalledWith(
      expect.stringContaining("--no-tls cannot be combined with --tls-fingerprint"),
    );
  });

  it("rejects an invalid TLS fingerprint before building an install plan", async () => {
    await runNodeDaemonInstall({ force: true, tlsFingerprint: "sha256:abc123" });

    expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
    expect(mocks.runtime.error).toHaveBeenCalledWith(
      expect.stringContaining("Invalid TLS fingerprint"),
    );
  });

  it("rejects Access credentials before installing a plaintext node service", async () => {
    mocks.loadNodeHostConfig.mockResolvedValue({
      gateway: {
        host: "saved-gateway.local",
        port: 18789,
        tls: false,
        cloudflareAccess: {
          clientId: "$CF_ACCESS_CLIENT_ID",
          clientSecret: "$CF_ACCESS_CLIENT_SECRET",
        },
      },
    });

    await runNodeDaemonInstall({ force: true });

    expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
    expect(mocks.runtime.error).toHaveBeenCalledWith(
      "Cloudflare Access credentials require --tls for the node Gateway connection",
    );
  });

  it.each([
    ["an invalid explicit port", { port: "abc" }, "Invalid --port"],
    ["an unsupported runtime", { runtime: "deno" }, 'Invalid --runtime (use "node" or "bun"'],
  ])("rejects %s before building an install plan", async (_name, opts, error) => {
    await runNodeDaemonInstall(opts);

    expect(mocks.runtime.error).toHaveBeenCalledWith(expect.stringContaining(error));
    expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
    expect(mocks.service.install).not.toHaveBeenCalled();
  });

  it("forwards Bun as the explicit node-service runtime", async () => {
    await runNodeDaemonInstall({ runtime: "bun", force: true });

    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
      expect.objectContaining({ runtime: "bun" }),
    );
  });

  it.each([false, true])(
    "rejects Nix installs before config or service inspection (json=%s)",
    async (json) => {
      await withEnvAsync({ OPENCLAW_NIX_MODE: "1" }, async () => {
        await runNodeDaemonInstall({ json, force: true });
      });

      const message = "Nix mode detected; service install is disabled.";
      expect(mocks.runtime.exit).toHaveBeenCalledExactlyOnceWith(1);
      expect(mocks.loadNodeHostConfig).not.toHaveBeenCalled();
      expect(mocks.service.isLoaded).not.toHaveBeenCalled();
      expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
      expect(mocks.service.install).not.toHaveBeenCalled();
      expect(mocks.runtime.log).not.toHaveBeenCalled();
      if (json) {
        expect(mocks.runtime.writeJson).toHaveBeenCalledExactlyOnceWith(
          expect.objectContaining({ action: "install", ok: false, error: message }),
        );
        expect(mocks.runtime.error).not.toHaveBeenCalled();
      } else {
        expect(mocks.runtime.error).toHaveBeenCalledExactlyOnceWith(message);
        expect(mocks.runtime.writeJson).not.toHaveBeenCalled();
      }
    },
  );

  it.each([
    {
      restriction: "external Gateway supervision",
      env: { OPENCLAW_SUPERVISOR_MODE: "external" },
    },
    {
      restriction: "noncanonical Gateway state",
      env: { OPENCLAW_STATE_DIR: "/tmp/openclaw-node-custom-state" },
    },
  ])("does not apply $restriction to Node installation", async ({ env }) => {
    mocks.service.isLoaded.mockResolvedValueOnce(false).mockResolvedValue(true);

    await withEnvAsync(env, async () => {
      await runNodeDaemonInstall({ json: true });
    });

    expect(mocks.buildNodeInstallPlan).toHaveBeenCalledOnce();
    expect(mocks.service.install).toHaveBeenCalledOnce();
    expect(mocks.runtime.writeJson).toHaveBeenCalledExactlyOnceWith(
      expect.objectContaining({
        action: "install",
        ok: true,
        result: "installed",
        service: expect.objectContaining({ label: "Node service", loaded: true }),
      }),
    );
    expect(mocks.runtime.error).not.toHaveBeenCalled();
    expect(mocks.runtime.exit).not.toHaveBeenCalled();
  });

  it("warns about disabled systemd lingering after a fresh install (text mode)", async () => {
    useLinuxPlatform();
    // isLoaded=true so the service-load verification passes and the linger
    // diagnostic runs on the verified-success path.
    mocks.service.isLoaded.mockResolvedValue(true);
    await runNodeDaemonInstall({ force: true });

    expect(mocks.readSystemdUserLingerStatus).toHaveBeenCalled();
    expect(mocks.runtime.log).toHaveBeenCalledWith(
      expect.stringContaining("sudo loginctl enable-linger pi"),
    );
  });

  it("checks lingering for the same sudo target user as the systemd service", async () => {
    useLinuxPlatform();
    mocks.service.isLoaded.mockResolvedValue(true);
    mocks.resolveSystemdUserServiceAccount.mockReturnValue("debian");
    mocks.readSystemdUserLingerStatus.mockResolvedValue({ user: "debian", linger: "no" });

    await runNodeDaemonInstall({ force: true });

    expect(mocks.resolveSystemdUserServiceAccount).toHaveBeenCalledWith(process.env);
    expect(mocks.readSystemdUserLingerStatus).toHaveBeenCalledWith({
      env: process.env,
      user: "debian",
    });
    expect(mocks.runtime.log).toHaveBeenCalledWith(
      expect.stringContaining("sudo loginctl enable-linger debian"),
    );
  });

  it("includes the linger warning in JSON warnings after a fresh install", async () => {
    useLinuxPlatform();
    mocks.service.isLoaded.mockResolvedValue(true);
    await runNodeDaemonInstall({ force: true, json: true });

    expect(mocks.runtime.writeJson).toHaveBeenCalledWith(
      expect.objectContaining({
        warnings: expect.arrayContaining([expect.stringContaining("enable-linger pi")]),
      }),
    );
  });

  it("warns about disabled lingering on the already-installed short-circuit path", async () => {
    useLinuxPlatform();
    mocks.service.isLoaded.mockResolvedValue(true);
    await runNodeDaemonInstall({ force: false });

    expect(mocks.readSystemdUserLingerStatus).toHaveBeenCalled();
    expect(mocks.runtime.log).toHaveBeenCalledWith(
      expect.stringContaining("sudo loginctl enable-linger pi"),
    );
  });

  it("does not warn when systemd lingering is already enabled", async () => {
    useLinuxPlatform();
    mocks.service.isLoaded.mockResolvedValue(true);
    mocks.readSystemdUserLingerStatus.mockResolvedValue({ user: "pi", linger: "yes" });
    await runNodeDaemonInstall({ force: true });

    expect(mocks.runtime.log).not.toHaveBeenCalledWith(expect.stringContaining("enable-linger"));
  });

  it("does not pollute the failure output when service.install throws", async () => {
    useLinuxPlatform();
    mocks.service.isLoaded.mockResolvedValue(true);
    mocks.service.install.mockRejectedValue(new Error("disk full"));
    await runNodeDaemonInstall({ force: true, json: true });

    // install() threw before verification, so onVerified never runs and no
    // linger warning accompanies the install-failure payload.
    const calls = mocks.runtime.writeJson.mock.calls;
    const failurePayload = calls
      .map(([payload]) => payload as { ok?: boolean; error?: string; warnings?: string[] })
      .find((payload) => payload.ok === false);
    expect(failurePayload).toBeDefined();
    expect(failurePayload?.error).toContain("install failed");
    expect(failurePayload?.warnings ?? []).toEqual(
      expect.not.arrayContaining([expect.stringContaining("enable-linger")]),
    );
  });

  it("does not warn when service-load verification fails (regression for #107033 review)", async () => {
    useLinuxPlatform();
    // install() succeeded but the service is not loaded: the linger diagnostic
    // must NOT run, so a failed verification never tells the operator to fix
    // lingering for a service that was not successfully installed.
    mocks.service.isLoaded.mockResolvedValue(false);
    await runNodeDaemonInstall({ force: true, json: true });

    expect(mocks.readSystemdUserLingerStatus).not.toHaveBeenCalled();
    const calls = mocks.runtime.writeJson.mock.calls;
    const failurePayload = calls
      .map(([payload]) => payload as { ok?: boolean; error?: string; warnings?: string[] })
      .find((payload) => payload.ok === false);
    expect(failurePayload).toBeDefined();
    expect(failurePayload?.error).toContain("verification failed");
    expect(failurePayload?.warnings ?? []).toEqual(
      expect.not.arrayContaining([expect.stringContaining("enable-linger")]),
    );
  });

  it("skips the linger check when systemd user services are unavailable", async () => {
    useLinuxPlatform();
    mocks.service.isLoaded.mockResolvedValue(true);
    mocks.isSystemdUserServiceAvailable.mockResolvedValue(false);
    await runNodeDaemonInstall({ force: true });

    expect(mocks.readSystemdUserLingerStatus).not.toHaveBeenCalled();
  });
});

describe("node daemon lifecycle adapters", () => {
  beforeEach(() => {
    mocks.runServiceRestart.mockReset();
    mocks.runServiceStart.mockReset();
    mocks.runServiceStop.mockReset();
    mocks.runServiceUninstall.mockReset();
  });

  it.each([
    {
      name: "start",
      action: runNodeDaemonStart,
      delegate: mocks.runServiceStart,
      expected: { renderStartHints: expect.any(Function) },
    },
    {
      name: "stop",
      action: runNodeDaemonStop,
      delegate: mocks.runServiceStop,
      expected: {},
    },
    {
      name: "restart",
      action: runNodeDaemonRestart,
      delegate: mocks.runServiceRestart,
      expected: { renderStartHints: expect.any(Function) },
    },
    {
      name: "uninstall",
      action: runNodeDaemonUninstall,
      delegate: mocks.runServiceUninstall,
      expected: {
        stopBeforeUninstall: false,
        assertNotLoadedAfterUninstall: false,
      },
    },
  ])(
    "delegates $name with node-specific service options",
    async ({ action, delegate, expected }) => {
      await action({ json: true });

      expect(delegate).toHaveBeenCalledWith(
        expect.objectContaining({
          serviceNoun: "Node",
          service: mocks.service,
          opts: { json: true },
          ...expected,
        }),
      );
    },
  );
});

describe("runNodeDaemonStatus", () => {
  function stdout(): string {
    return mocks.runtime.log.mock.calls.map(([line]) => line).join("\n");
  }

  function stderr(): string {
    return mocks.runtime.error.mock.calls.map(([line]) => line).join("\n");
  }

  beforeEach(() => {
    mocks.runtime.log.mockClear();
    mocks.runtime.error.mockClear();
    mocks.runtime.writeJson.mockClear();
    mocks.runtime.exit.mockClear();
    mocks.service.isLoaded.mockReset().mockResolvedValue(true);
    mocks.service.readCommand.mockReset().mockResolvedValue(null);
    mocks.service.readRuntime.mockReset().mockResolvedValue({ status: "running" });
  });

  it("reports a failed service check instead of claiming the node is not installed", async () => {
    mocks.service.isLoaded.mockRejectedValue(new Error("systemd unavailable"));

    await runNodeDaemonStatus();

    expect(mocks.runtime.error).toHaveBeenCalledWith(
      "Node service check failed: systemd unavailable",
    );
    expect(mocks.runtime.exit).toHaveBeenCalledWith(1);
    expect(stdout()).not.toContain("not loaded");
    expect(stdout()).not.toContain("openclaw node install");
  });

  it("reports a failed service check as JSON without inventing node status", async () => {
    const secret = "sk-abcdefghijklmnopqrstuv";
    const error = new Error(`systemd unavailable: Authorization: Bearer ${secret}`);
    error.name = "ServiceManagerError";
    mocks.service.isLoaded.mockRejectedValue(error);

    await expect(runNodeDaemonStatus({ json: true })).rejects.toThrow(
      "Node service check failed: systemd unavailable",
    );

    expect(mocks.runtime.writeJson).not.toHaveBeenCalled();
    expect(mocks.runtime.exit).not.toHaveBeenCalled();
    expect(mocks.runtime.error).not.toHaveBeenCalled();
  });

  it("reports an unknown runtime when runtime inspection fails", async () => {
    const error = new Error("permission denied");
    error.name = "RuntimeInspectionError";
    mocks.service.readRuntime.mockRejectedValue(error);

    await runNodeDaemonStatus({ json: true });

    expect(mocks.runtime.writeJson).toHaveBeenCalledWith({
      service: expect.objectContaining({
        runtime: { status: "unknown", detail: "permission denied" },
      }),
    });
    expect(JSON.stringify(mocks.runtime.writeJson.mock.calls)).not.toContain(error.name);
  });

  it("keeps missing service-unit status on stderr and prints recovery hints on stdout", async () => {
    mocks.service.readRuntime.mockResolvedValue({ status: "stopped", missingUnit: true });

    await runNodeDaemonStatus();

    expect(stderr()).toContain("Service unit not found.");
    expect(stdout()).toContain("Logs: node service log");
    expect(stdout()).toContain("Restart attempts: node restart log");
    expect(stderr()).not.toContain("Logs: node service log");
    expect(stderr()).not.toContain("Restart attempts: node restart log");
  });

  it("keeps stopped status on stderr and prints recovery hints on stdout", async () => {
    mocks.service.readRuntime.mockResolvedValue({ status: "stopped" });

    await runNodeDaemonStatus();

    expect(stderr()).toContain("Service is loaded but not running.");
    expect(stdout()).toContain("Logs: node service log");
    expect(stdout()).toContain("Restart attempts: node restart log");
    expect(stderr()).not.toContain("Logs: node service log");
    expect(stderr()).not.toContain("Restart attempts: node restart log");
  });

  it("redacts service credentials from JSON status output", async () => {
    const command: GatewayServiceCommandConfig = {
      programArguments: ["node", "node-host"],
      environment: {
        OPENCLAW_PROFILE: "work",
        OPENCLAW_GATEWAY_TOKEN: "gateway-token",
        OPENCLAW_GATEWAY_PASSWORD: "gateway-password",
      },
      managedDefinition: {
        programArguments: ["node", "node-host"],
        environment: { OPENCLAW_GATEWAY_TOKEN: "managed-base-token" },
      },
      managedOverrides: { launcher: "command", environment: { keys: ["OPENCLAW_GATEWAY_TOKEN"] } },
      definitionPaths: ["/etc/systemd/user/node-definition.conf"],
      environmentValueSources: { OPENCLAW_PROFILE: "file" },
      reloadPending: true,
    };
    mocks.service.readCommand.mockResolvedValue(command);

    await runNodeDaemonStatus({ json: true });

    expect(mocks.runtime.writeJson).toHaveBeenCalledWith({
      service: expect.objectContaining({
        command: expect.objectContaining({
          environment: { OPENCLAW_PROFILE: "work" },
          definitionPaths: command.definitionPaths,
          environmentValueSources: command.environmentValueSources,
          reloadPending: true,
        }),
      }),
    });
    const payload = JSON.stringify(mocks.runtime.writeJson.mock.calls[0]?.[0]);
    expect(payload).not.toContain("gateway-token");
    expect(payload).not.toContain("gateway-password");
    expect(payload).not.toContain("managed-base-token");
    expect(payload).not.toContain("managedDefinition");
    expect(payload).not.toContain("managedOverrides");
    expect(command.environment?.OPENCLAW_GATEWAY_TOKEN).toBe("gateway-token");
    expect(command.managedDefinition).toBeDefined();
    expect(command.managedOverrides).toBeDefined();
  });
});