Skip to content

Commit 383f894

Browse files
authored
fix: doctor skips host services for isolated state (#115922)
* fix(doctor): isolate host service management * fix(doctor): clarify service isolation recovery * test(doctor): isolate service identity fixtures * test(daemon): keep lifecycle fixtures lint-clean * test(daemon): isolate install identity fixtures
1 parent 6ec3dbd commit 383f894

27 files changed

Lines changed: 442 additions & 22 deletions

‎src/cli/daemon-cli.coverage.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,11 @@ const mocks = await vi.hoisted(async () => {
8787

8888
const { runtimeLogs } = mocks;
8989

90+
vi.mock("../config/paths.js", async () => {
91+
const actual = await vi.importActual<typeof import("../config/paths.js")>("../config/paths.js");
92+
return { ...actual, isDefaultInstallIdentity: () => true };
93+
});
94+
9095
vi.mock("./daemon-cli/probe.js", () => ({
9196
probeGatewayStatus: (opts: unknown) => probeGatewayStatus(opts),
9297
}));

‎src/cli/daemon-cli/install.integration.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ const serviceMock = vi.hoisted(() => ({
2222
readRuntime: vi.fn(async () => ({ status: "stopped" as const })),
2323
}));
2424

25+
vi.mock("../../config/paths.js", async () => {
26+
const actual =
27+
await vi.importActual<typeof import("../../config/paths.js")>("../../config/paths.js");
28+
return { ...actual, isDefaultInstallIdentity: () => true };
29+
});
30+
2531
vi.mock("../../daemon/service.js", () => ({
2632
resolveGatewayService: () => serviceMock,
2733
}));

‎src/cli/daemon-cli/install.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const resolveNodeStartupTlsEnvironmentMock = vi.hoisted(() => vi.fn());
1313
const loadConfigMock = vi.hoisted(() => vi.fn());
1414
const readConfigFileSnapshotMock = vi.hoisted(() => vi.fn());
1515
const resolveGatewayPortMock = vi.hoisted(() => vi.fn(() => 18789));
16+
const isDefaultInstallIdentityMock = vi.hoisted(() => vi.fn(() => true));
1617
const replaceConfigFileMock = vi.hoisted(() => vi.fn());
1718
const resolveIsNixModeMock = vi.hoisted(() => vi.fn(() => false));
1819
const resolveSecretInputRefMock = vi.hoisted(() =>
@@ -102,6 +103,7 @@ vi.mock("../../config/mutate.js", () => ({
102103
}));
103104

104105
vi.mock("../../config/paths.js", () => ({
106+
isDefaultInstallIdentity: isDefaultInstallIdentityMock,
105107
resolveGatewayPort: resolveGatewayPortMock,
106108
resolveIsNixMode: resolveIsNixModeMock,
107109
}));
@@ -276,6 +278,7 @@ describe("runDaemonInstall", () => {
276278
resolveNodeStartupTlsEnvironmentMock.mockReset();
277279
readConfigFileSnapshotMock.mockReset();
278280
resolveGatewayPortMock.mockClear();
281+
isDefaultInstallIdentityMock.mockReturnValue(true);
279282
replaceConfigFileMock.mockReset();
280283
resolveIsNixModeMock.mockReset();
281284
resolveSecretInputRefMock.mockReset();
@@ -362,6 +365,20 @@ describe("runDaemonInstall", () => {
362365
expect(installDaemonServiceAndEmitMock).not.toHaveBeenCalled();
363366
});
364367

368+
it("blocks non-default install identities before inspecting host services", async () => {
369+
isDefaultInstallIdentityMock.mockReturnValue(false);
370+
371+
await runDaemonInstall({ json: true });
372+
373+
expect(actionState.failed[0]?.message).toContain(
374+
"service management skipped: non-default state dir or config path",
375+
);
376+
expect(readConfigFileSnapshotMock).not.toHaveBeenCalled();
377+
expect(service.isLoaded).not.toHaveBeenCalled();
378+
expect(service.readCommand).not.toHaveBeenCalled();
379+
expect(installDaemonServiceAndEmitMock).not.toHaveBeenCalled();
380+
});
381+
365382
it("validates token SecretRef but does not serialize resolved token into service env", async () => {
366383
mockResolvedGatewayTokenSecretRef();
367384

‎src/cli/daemon-cli/install.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,7 @@ import {
2525
isLoopbackHost,
2626
resolveGatewayBindHost,
2727
} from "../../gateway/net.js";
28-
import {
29-
formatExternalSupervisorActionRequired,
30-
isGatewayExternallySupervised,
31-
} from "../../infra/gateway-supervision.js";
28+
import { assertGatewayServiceMutationAllowed } from "../../infra/gateway-supervision.js";
3229
import {
3330
isDangerousHostEnvOverrideVarName,
3431
isDangerousHostEnvVarName,
@@ -149,10 +146,10 @@ export async function runDaemonInstall(opts: DaemonInstallOptions) {
149146
if (failIfNixDaemonInstallMode(fail)) {
150147
return;
151148
}
152-
if (isGatewayExternallySupervised()) {
153-
fail(
154-
`Gateway install blocked: ${formatExternalSupervisorActionRequired("install or rewrite the gateway service")}`,
155-
);
149+
try {
150+
assertGatewayServiceMutationAllowed("install or rewrite the gateway service");
151+
} catch (error) {
152+
fail(`Gateway install blocked: ${String(error)}`);
156153
return;
157154
}
158155

‎src/cli/daemon-cli/lifecycle.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ vi.mock("../../config/config.js", () => ({
129129
resolveGatewayPort: (cfg?: unknown, env?: unknown) => resolveGatewayPort(cfg, env),
130130
}));
131131

132+
vi.mock("../../config/paths.js", () => ({ isDefaultInstallIdentity: () => true }));
133+
132134
vi.mock("../../infra/gateway-processes.js", () => ({
133-
findVerifiedGatewayListenerPidsOnPortSync: (port: number) =>
134-
findVerifiedGatewayListenerPidsOnPortSync(port),
135+
findVerifiedGatewayListenerPidsOnPortSync,
135136
signalVerifiedGatewayPidSync: (pid: number, signal: "SIGTERM" | "SIGUSR1") =>
136137
signalVerifiedGatewayPidSync(pid, signal),
137138
formatGatewayPidList: (pids: number[]) => formatGatewayPidList(pids),

‎src/cli/daemon-cli/start-repair.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ const resolveGatewayPortMock = vi.hoisted(() => vi.fn(() => 18789));
3434
const resolveOpenClawWrapperPathMock = vi.hoisted(() => vi.fn());
3535
const formatGatewayServiceStartRepairIssuesMock = vi.hoisted(() => vi.fn());
3636
const defaultRuntimeLogMock = vi.hoisted(() => vi.fn());
37+
const assertGatewayServiceMutationAllowedMock = vi.hoisted(() => vi.fn());
3738

3839
vi.mock("../../commands/daemon-install-helpers.js", () => ({
3940
buildGatewayInstallPlan: buildGatewayInstallPlanMock,
@@ -64,6 +65,10 @@ vi.mock("../../daemon/service.js", () => ({
6465
formatGatewayServiceStartRepairIssues: formatGatewayServiceStartRepairIssuesMock,
6566
}));
6667

68+
vi.mock("../../infra/gateway-supervision.js", () => ({
69+
assertGatewayServiceMutationAllowed: assertGatewayServiceMutationAllowedMock,
70+
}));
71+
6772
vi.mock("../../runtime.js", () => ({
6873
defaultRuntime: { log: defaultRuntimeLogMock },
6974
}));
@@ -87,6 +92,7 @@ describe("repairLoadedGatewayServiceForStart", () => {
8792
resolveOpenClawWrapperPathMock.mockReset();
8893
formatGatewayServiceStartRepairIssuesMock.mockReset();
8994
defaultRuntimeLogMock.mockClear();
95+
assertGatewayServiceMutationAllowedMock.mockReset();
9096

9197
resolveGatewayInstallTokenMock.mockResolvedValue({
9298
tokenRefConfigured: false,

‎src/cli/daemon-cli/start-repair.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type {
1212
GatewayServiceState,
1313
} from "../../daemon/service.js";
1414
import { formatGatewayServiceStartRepairIssues } from "../../daemon/service.js";
15+
import { assertGatewayServiceMutationAllowed } from "../../infra/gateway-supervision.js";
1516
import { parseTcpPort, parseTcpPortFromArgs } from "../../infra/tcp-port.js";
1617
import { defaultRuntime } from "../../runtime.js";
1718
import { mergeInstallInvocationEnv } from "./install.js";
@@ -48,6 +49,7 @@ export async function repairLoadedGatewayServiceForStart(
4849
warnings?: string[];
4950
loaded: boolean;
5051
}> {
52+
assertGatewayServiceMutationAllowed("repair the gateway service");
5153
const { snapshot: configSnapshot, writeOptions: configWriteOptions } =
5254
await readConfigFileSnapshotForWrite();
5355
const cfg = configSnapshot.valid ? configSnapshot.sourceConfig : configSnapshot.config;

‎src/commands/doctor-gateway-daemon-flow.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ const findSystemGatewayServices = vi.hoisted(() =>
3535
);
3636
const buildGatewayRuntimeHints = vi.hoisted(() => vi.fn((): string[] => []));
3737
const formatGatewayRuntimeSummary = vi.hoisted(() => vi.fn((): string | null => null));
38+
const isDefaultInstallIdentity = vi.hoisted(() => vi.fn(() => true));
3839

3940
vi.mock("../config/config.js", async () => {
4041
const actual = await vi.importActual<typeof import("../config/config.js")>("../config/config.js");
@@ -44,6 +45,11 @@ vi.mock("../config/config.js", async () => {
4445
};
4546
});
4647

48+
vi.mock("../config/paths.js", async () => {
49+
const actual = await vi.importActual<typeof import("../config/paths.js")>("../config/paths.js");
50+
return { ...actual, isDefaultInstallIdentity };
51+
});
52+
4753
vi.mock("../daemon/constants.js", () => ({
4854
resolveGatewayLaunchAgentLabel: vi.fn(() => "ai.openclaw.gateway"),
4955
resolveNodeLaunchAgentLabel: vi.fn(() => "ai.openclaw.node"),
@@ -161,6 +167,7 @@ describe("maybeRepairGatewayDaemon", () => {
161167
service.readRuntime.mockResolvedValue({ status: "running" });
162168
service.readCommand.mockResolvedValue(null);
163169
service.restart.mockResolvedValue({ outcome: "completed" });
170+
isDefaultInstallIdentity.mockReturnValue(true);
164171
readGatewayRestartHandoffSync.mockReturnValue(null);
165172
findSystemGatewayServices.mockResolvedValue([]);
166173
inspectPortUsage.mockResolvedValue({
@@ -287,6 +294,41 @@ describe("maybeRepairGatewayDaemon", () => {
287294
await runScheduledGatewayRepairAndExpectVerificationSkipped("Restart gateway service now?");
288295
});
289296

297+
it("skips every service-manager seam for a non-default install identity", async () => {
298+
await withEnvAsync(
299+
{
300+
OPENCLAW_STATE_DIR: "/tmp/openclaw-copied-state",
301+
OPENCLAW_CONFIG_PATH: "/tmp/openclaw-copied-state/openclaw.json",
302+
},
303+
async () => {
304+
isDefaultInstallIdentity.mockReturnValue(false);
305+
await runNonInteractiveRepair();
306+
},
307+
);
308+
309+
expect(service.isLoaded).not.toHaveBeenCalled();
310+
expect(service.readRuntime).not.toHaveBeenCalled();
311+
expect(service.readCommand).not.toHaveBeenCalled();
312+
expect(service.install).not.toHaveBeenCalled();
313+
expect(service.restart).not.toHaveBeenCalled();
314+
expect(launchd.repairLaunchAgentBootstrap).not.toHaveBeenCalled();
315+
expect(findSystemGatewayServices).not.toHaveBeenCalled();
316+
expect(note).toHaveBeenCalledWith(
317+
"service management skipped: non-default state dir or config path",
318+
"Gateway",
319+
);
320+
});
321+
322+
it("still inspects the managed service for the default install identity", async () => {
323+
await withEnvAsync(
324+
{ OPENCLAW_STATE_DIR: undefined, OPENCLAW_CONFIG_PATH: undefined },
325+
runNonInteractiveRepair,
326+
);
327+
328+
expect(service.isLoaded).toHaveBeenCalledTimes(1);
329+
expect(service.readRuntime).toHaveBeenCalledTimes(1);
330+
});
331+
290332
it("reports recent restart handoffs during deep doctor", async () => {
291333
vi.useFakeTimers();
292334
vi.setSystemTime(40_000);

‎src/commands/doctor-gateway-daemon-flow.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { note } from "../../packages/terminal-core/src/note.js";
33
import { formatCliCommand } from "../cli/command-format.js";
44
import { resolveGatewayPort } from "../config/config.js";
5+
import { isDefaultInstallIdentity } from "../config/paths.js";
56
import type { OpenClawConfig } from "../config/types.openclaw.js";
67
import {
78
resolveGatewayLaunchAgentLabel,
@@ -18,6 +19,7 @@ import type { GatewayServiceRuntime } from "../daemon/service-runtime.js";
1819
import { describeGatewayServiceRestart, resolveGatewayService } from "../daemon/service.js";
1920
import { renderSystemdUnavailableHints } from "../daemon/systemd-hints.js";
2021
import { isSystemdUserServiceAvailable } from "../daemon/systemd.js";
22+
import { NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON } from "../infra/gateway-supervision.js";
2123
import {
2224
formatPortDiagnostics,
2325
inspectPortConnections,
@@ -193,6 +195,10 @@ export async function maybeRepairGatewayDaemon(params: {
193195
healthOk: boolean;
194196
healthSkipped?: boolean;
195197
}) {
198+
if (!isDefaultInstallIdentity(process.env)) {
199+
note(NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON, "Gateway");
200+
return;
201+
}
196202
if (params.healthOk) {
197203
await maybeReportEstablishedGatewayClients({
198204
cfg: params.cfg,

‎src/commands/doctor-gateway-services.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ const mocks = vi.hoisted(() => ({
3939
resolveGatewayAuthTokenForService: vi.fn(),
4040
resolveGatewayPort: vi.fn(() => 18789),
4141
resolveIsNixMode: vi.fn(() => false),
42+
isDefaultInstallIdentity: vi.fn(() => true),
4243
findExtraGatewayServices: vi.fn().mockResolvedValue([]),
4344
renderGatewayServiceCleanupHints: vi.fn().mockReturnValue([]),
4445
needsNodeRuntimeMigration: vi.fn(() => false),
@@ -53,6 +54,7 @@ const mocks = vi.hoisted(() => ({
5354
}));
5455

5556
vi.mock("../config/paths.js", () => ({
57+
isDefaultInstallIdentity: mocks.isDefaultInstallIdentity,
5658
resolveGatewayPort: mocks.resolveGatewayPort,
5759
resolveIsNixMode: mocks.resolveIsNixMode,
5860
}));
@@ -421,6 +423,7 @@ describe("maybeRepairGatewayServiceConfig", () => {
421423
vi.clearAllMocks();
422424
fsMocks.realpath.mockImplementation(async (value: string) => value);
423425
mocks.resolveGatewayPort.mockReturnValue(18789);
426+
mocks.isDefaultInstallIdentity.mockReturnValue(true);
424427
mocks.readRuntime.mockResolvedValue({ status: "unknown" });
425428
mocks.readWindowsStartupFallbackRuntimeForUpdate.mockResolvedValue(null);
426429
mocks.needsNodeRuntimeMigration.mockReturnValue(false);
@@ -486,6 +489,21 @@ describe("maybeRepairGatewayServiceConfig", () => {
486489
expectNoteContaining("adaptive default", "Gateway heap");
487490
});
488491

492+
it("skips service audit and rewrite for a non-default install identity", async () => {
493+
mocks.isDefaultInstallIdentity.mockReturnValue(false);
494+
495+
await runRepair({ gateway: {} });
496+
497+
expect(mocks.readCommand).not.toHaveBeenCalled();
498+
expect(mocks.auditGatewayServiceConfig).not.toHaveBeenCalled();
499+
expect(mocks.stage).not.toHaveBeenCalled();
500+
expect(mocks.install).not.toHaveBeenCalled();
501+
expectNoteContaining(
502+
"service management skipped: non-default state dir or config path",
503+
"Gateway",
504+
);
505+
});
506+
489507
it("treats gateway.auth.token as source of truth for service token repairs", async () => {
490508
setupGatewayTokenRepairScenario();
491509

0 commit comments

Comments
 (0)