Skip to content

Commit fda20a6

Browse files
authored
fix(systemd): honor effective drop-in configuration (#129170)
* fix(systemd): honor effective drop-in configuration Read one coherent manager-loaded service snapshot while retaining the managed base definition for repairs. Track drop-in ownership, surface pending daemon reloads, and keep update and doctor rewrites from adopting operator-owned values. Closes #128929 * fix(systemd): expose reload status in service snapshot * test(systemd): cover Linux doctor ownership
1 parent 9557a47 commit fda20a6

24 files changed

Lines changed: 1669 additions & 290 deletions

‎docs/cli/doctor.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ compare restored legacy artifacts with the SQLite rows before importing.
420420
- If `openclaw.json` cannot be parsed and no last-known-good config can be recovered, `doctor --fix` leaves the file unchanged and exits with an error instead of writing a partial replacement. The error points to `openclaw config validate` for the exact parse position and explains how to edit or regenerate the config.
421421
- Set `OPENCLAW_SERVICE_REPAIR_POLICY=external` when another supervisor owns the gateway lifecycle. Doctor still reports gateway/service health and applies non-service repairs, but skips service install/start/restart/bootstrap and legacy service cleanup.
422422
- Doctor reports the managed Gateway's applied heap limit and the adaptive derivation used for the current host or container memory limit. Use `openclaw gateway status` for the same report outside a repair pass.
423-
- On Linux, doctor ignores inactive extra gateway-like systemd units and does not rewrite command/entrypoint metadata for a running systemd gateway service during repair. Stop the service first, or use `openclaw gateway install --force` to replace the active launcher.
423+
- On Linux, doctor ignores inactive extra gateway-like systemd units and does not rewrite command/entrypoint metadata for a running systemd gateway service during repair. Stop the service first, or use `openclaw gateway install --force` to rewrite the managed base unit. If a systemd drop-in overrides `ExecStart=` or `WorkingDirectory=`, inspect it with `systemctl --user cat <unit>.service` and update or remove that drop-in yourself; reinstalling the base does not replace it. `Environment=` drop-ins remain supported.
424424
- `doctor --fix --non-interactive` reports missing or stale gateway service definitions but does not install or rewrite them outside update repair mode. Run `openclaw gateway install` for a missing service, or `openclaw gateway install --force` to replace the launcher.
425425
- State integrity checks detect orphan transcript files in the sessions directory. Archiving them as `.deleted.<timestamp>` requires interactive confirmation; `--fix`, `--yes`, and headless runs leave them in place.
426426
- Doctor scans historical `~/.openclaw/cron/jobs.json` stores and previously configured legacy store locations for old cron job shapes, imports jobs and quarantine records into SQLite, and archives the migrated JSON files.

‎docs/cli/gateway.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ openclaw gateway status --require-rpc
378378
- Use `--require-rpc` in scripts/automation when a listening service is not enough and you need read-scope RPC to be healthy too.
379379
- `--deep` scans for extra launchd/systemd/schtasks installs; when multiple gateway-like services are found, human output prints cleanup hints (usually run one gateway per machine) and reports a recent supervisor restart handoff when relevant.
380380
- `--deep` also runs config validation in plugin-aware mode (`pluginValidation: "full"`) and surfaces plugin manifest warnings (e.g. missing channel config metadata). Default `gateway status` keeps the fast read-only path that skips plugin validation.
381+
- On Linux, status reports the effective service currently loaded by systemd, including loaded drop-ins. If the unit or a drop-in changed on disk, `Systemd reload: pending` means you must run `systemctl --user daemon-reload` (or `sudo systemctl daemon-reload` for a system service) before those changes take effect.
381382
- Human output includes the resolved file log path plus CLI-vs-service config paths/validity to help diagnose profile or state-dir drift.
382383
- Human output includes `Gateway heap:` with the applied limit and its adaptive derivation. JSON output exposes the same report as `service.gatewayHeap`.
383384

@@ -602,6 +603,7 @@ openclaw gateway restart
602603
- `gateway start` is idempotent: when the managed service is already running, it reports the running process and leaves it untouched. A loaded but stopped service is started as before.
603604
- If no managed service is installed, `gateway start` prints install hints and exits nonzero. `gateway restart` can first recover an installed-but-unloaded LaunchAgent or a verified unmanaged Gateway; if neither a managed service nor recovery handles the action, it prints the same hints and exits nonzero. Stopping an absent service remains a successful no-op.
604605
- If `gateway start` or `gateway restart` needs to repair a stale service definition, the command refuses when the invoking shell resolves a different state directory, config path, or port than the installed service. Match or unset the conflicting environment overrides, or use `openclaw gateway install --force` to retarget the service intentionally.
606+
- On Linux, `gateway start` and `gateway restart` also refuse ineffective repairs when an operator-owned systemd drop-in overrides the command or working directory. Inspect the effective unit with `systemctl --user cat <unit>.service`, then update or remove that drop-in. `gateway install --force` rewrites only the managed base unit and warns if the override remains; `Environment=` drop-ins remain supported.
605607
- Use `gateway restart` to restart a managed service. Do not chain `gateway stop` and `gateway start` as a restart substitute.
606608
- In a non-interactive shell, `gateway stop` requires `--force`. Interactive terminals keep the existing prompt-free behavior. For automation and tests, prefer `gateway run --dev` or an isolated `--profile` with a free port.
607609
- On macOS, `gateway stop` uses `launchctl bootout` by default, which removes the LaunchAgent from the current boot session without persisting a disable — KeepAlive auto-recovery stays active for future crashes and `gateway start` re-enables cleanly without a manual `launchctl enable`. Pass `--disable` to persistently suppress KeepAlive and RunAtLoad so the gateway does not respawn until the next explicit `gateway start`; use this when a manual stop should survive reboots.

‎docs/gateway/doctor.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -598,18 +598,18 @@ That stages grounded durable candidates into the short-term dreaming store while
598598
- `openclaw doctor` prompts before rewriting supervisor config.
599599
- `openclaw doctor --yes` accepts the default repair prompts.
600600
- `openclaw doctor --fix` applies recommended fixes without prompts (`--repair` is an alias).
601-
- `openclaw doctor --fix --force` overwrites custom supervisor configs.
601+
- `openclaw doctor --fix --force` can overwrite the managed supervisor config; operator-owned systemd drop-ins remain unchanged.
602602
- `OPENCLAW_SERVICE_REPAIR_POLICY=external` keeps doctor read-only for gateway service lifecycle. It still reports service health and runs non-service repairs, but skips service install/start/restart/bootstrap, supervisor config rewrites, and legacy service cleanup because an external supervisor owns that lifecycle.
603603
- On macOS, a same-label system LaunchDaemon blocks user LaunchAgent install, start, restart, and bootstrap repair. Doctor reports the system owner and stops service recovery; `--force` does not bypass this ownership boundary. See [Existing system LaunchDaemons](/gateway#existing-system-launchdaemons).
604-
- On Linux, doctor does not rewrite command/entrypoint metadata while the matching systemd gateway unit is active. It also ignores inactive non-legacy extra gateway-like units during the duplicate-service scan so companion service files do not create cleanup noise.
604+
- On Linux, doctor does not rewrite command/entrypoint metadata while the matching systemd gateway unit is active. If a stopped unit's command or working directory is overridden by an operator-owned systemd drop-in, inspect it with `systemctl --user cat <unit>.service`, then update or remove the drop-in; rewriting the managed base cannot change the effective launcher. `Environment=` drop-ins remain supported. Doctor also ignores inactive non-legacy extra gateway-like units during the duplicate-service scan so companion service files do not create cleanup noise.
605605
- If token auth requires a token and `gateway.auth.token` is SecretRef-managed, doctor service install/repair validates the SecretRef but does not persist resolved plaintext token values into supervisor service environment metadata.
606606
- Doctor detects managed `.env`/SecretRef-backed service environment values that older LaunchAgent, systemd, or Windows Scheduled Task installs embedded inline and rewrites the service metadata so those values load from the runtime source instead of the supervisor definition.
607607
- Doctor detects when the service command still pins an old `--port` after `gateway.port` changes and rewrites the service metadata to the current port.
608608
- If token auth requires a token and the configured token SecretRef is unresolved, doctor blocks the install/repair path with actionable guidance.
609609
- If both `gateway.auth.token` and `gateway.auth.password` are configured and `gateway.auth.mode` is unset, doctor blocks install/repair until mode is set explicitly.
610610
- For Linux user-systemd units, doctor token drift checks include both `Environment=` and `EnvironmentFile=` sources when comparing service auth metadata.
611611
- Doctor service repairs refuse to rewrite, stop, or restart a gateway service from an older OpenClaw binary when the config was last written by a newer version. See [Gateway troubleshooting](/gateway/troubleshooting#split-brain-installs-and-newer-config-guard).
612-
- You can always force a full rewrite via `openclaw gateway install --force`.
612+
- `openclaw gateway install --force` rewrites the managed base unit, but never removes operator-owned systemd drop-ins; it warns if a command or working-directory override remains effective.
613613

614614
</Accordion>
615615
<Accordion title="16. Gateway runtime + port diagnostics">

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

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -834,26 +834,43 @@ describe("runDaemonInstall", () => {
834834
expectLastEmittedResult("already-installed");
835835
});
836836

837-
it("preserves wrapper env from an installed but unloaded service during forced reinstall", async () => {
837+
it("preserves managed base wrapper, environment, and provenance during forced reinstall", async () => {
838+
for (const key of ["OPENAI_API_KEY", "OPENCLAW_WRAPPER"]) {
839+
delete process.env[key];
840+
}
841+
const environment = {
842+
OPENAI_API_KEY: "managed-service-key",
843+
OPENCLAW_WRAPPER: "/usr/local/bin/openclaw-doppler",
844+
};
845+
const environmentValueSources = {
846+
OPENAI_API_KEY: "file",
847+
OPENCLAW_WRAPPER: "inline",
848+
};
838849
service.isLoaded.mockResolvedValue(false);
839850
service.readCommand.mockResolvedValue({
840-
programArguments: ["/usr/local/bin/openclaw-doppler", "gateway", "run"],
851+
programArguments: ["/operator/drop-in-wrapper", "gateway", "run"],
841852
environment: {
842-
OPENCLAW_WRAPPER: "/usr/local/bin/openclaw-doppler",
853+
OPENAI_API_KEY: "operator-drop-in-key",
854+
OPENCLAW_WRAPPER: "/operator/drop-in-wrapper",
855+
},
856+
environmentValueSources: { OPENAI_API_KEY: "inline" },
857+
managedDefinition: {
858+
programArguments: [environment.OPENCLAW_WRAPPER, "gateway", "run"],
859+
environment,
860+
environmentValueSources,
843861
},
844862
} as never);
845863

846864
await runDaemonInstall({ json: true, force: true });
847865

848866
expect(service.readCommand).toHaveBeenCalledTimes(1);
849867
const installPlanArg = readFirstInstallPlanArg();
850-
expectFields(installPlanArg, { wrapperPath: "/usr/local/bin/openclaw-doppler" });
851-
expectFields(installPlanArg.existingEnvironment, {
852-
OPENCLAW_WRAPPER: "/usr/local/bin/openclaw-doppler",
853-
});
854-
expectFields(installPlanArg.env, {
855-
OPENCLAW_WRAPPER: "/usr/local/bin/openclaw-doppler",
868+
expectFields(installPlanArg, {
869+
wrapperPath: environment.OPENCLAW_WRAPPER,
870+
existingEnvironment: environment,
871+
existingEnvironmentValueSources: environmentValueSources,
856872
});
873+
expectFields(installPlanArg.env, environment);
857874
expect(installDaemonServiceAndEmitMock).toHaveBeenCalledTimes(1);
858875
});
859876

@@ -959,20 +976,24 @@ describe("runDaemonInstall", () => {
959976
);
960977
});
961978

962-
it("does not reinstall when OPENCLAW_GATEWAY_TOKEN comes from an env file", async () => {
979+
it.each([
980+
{ name: "an env file", source: "file", operatorOwned: false },
981+
{ name: "an operator-only drop-in", source: "inline", operatorOwned: true },
982+
])("does not reinstall when OPENCLAW_GATEWAY_TOKEN comes from $name", async (testCase) => {
963983
service.isLoaded.mockResolvedValue(true);
984+
const programArguments = ["openclaw", "gateway", "run"];
964985
service.readCommand.mockResolvedValue({
965-
programArguments: ["openclaw", "gateway", "run"],
966-
environment: {
967-
OPENCLAW_GATEWAY_TOKEN: "env-file-token",
968-
},
969-
environmentValueSources: {
970-
OPENCLAW_GATEWAY_TOKEN: "file",
971-
},
986+
programArguments,
987+
environment: { OPENCLAW_GATEWAY_TOKEN: "operator-token" },
988+
environmentValueSources: { OPENCLAW_GATEWAY_TOKEN: testCase.source },
989+
...(testCase.operatorOwned && {
990+
managedDefinition: { programArguments, environment: {} },
991+
}),
972992
} as never);
973993

974994
await runDaemonInstall({ json: true });
975995

996+
expect(buildGatewayInstallPlanMock).not.toHaveBeenCalled();
976997
expect(installDaemonServiceAndEmitMock).not.toHaveBeenCalled();
977998
expectLastEmittedResult("already-installed");
978999
});

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ import type { GatewayBindMode } from "../../config/types.gateway.js";
1616
import type { OpenClawConfig } from "../../config/types.js";
1717
import { OPENCLAW_WRAPPER_ENV_KEY, resolveOpenClawWrapperPath } from "../../daemon/program-args.js";
1818
import { readEmbeddedGatewayToken } from "../../daemon/service-audit.js";
19-
import { resolveGatewayService } from "../../daemon/service.js";
20-
import type { GatewayServiceCommandConfig } from "../../daemon/service.js";
19+
import { resolveManagedGatewayServiceCommand } from "../../daemon/service-types.js";
20+
import { resolveGatewayService, type GatewayServiceCommandConfig } from "../../daemon/service.js";
2121
import { isNonFatalSystemdInstallProbeError } from "../../daemon/systemd.js";
2222
import { resolveGatewayAuth } from "../../gateway/auth.js";
2323
import {
@@ -238,8 +238,9 @@ export async function runDaemonInstall(opts: DaemonInstallOptions) {
238238
}
239239
}
240240
const existingServiceCommand = await service.readCommand(process.env).catch(() => null);
241+
const existingManagedCommand = resolveManagedGatewayServiceCommand(existingServiceCommand);
241242
const existingServiceEnv: Record<string, string> | undefined =
242-
existingServiceCommand?.environment;
243+
existingManagedCommand?.environment;
243244
const installEnv = mergeInstallInvocationEnv({
244245
env: process.env,
245246
existingServiceEnv,
@@ -267,14 +268,14 @@ export async function runDaemonInstall(opts: DaemonInstallOptions) {
267268
if (loaded) {
268269
if (!opts.force) {
269270
const autoRefreshMessage = await getGatewayServiceAutoRefreshMessage({
270-
currentCommand: existingServiceCommand,
271+
currentCommand: existingManagedCommand,
271272
env: process.env,
272273
installEnv,
273274
port,
274275
runtime: runtimeRaw,
275276
wrapperPath,
276277
existingEnvironment: existingServiceEnv,
277-
existingEnvironmentValueSources: existingServiceCommand?.environmentValueSources,
278+
existingEnvironmentValueSources: existingManagedCommand?.environmentValueSources,
278279
config: cfg,
279280
});
280281
if (autoRefreshMessage) {
@@ -330,7 +331,7 @@ export async function runDaemonInstall(opts: DaemonInstallOptions) {
330331
runtime: runtimeRaw,
331332
wrapperPath,
332333
existingEnvironment: existingServiceEnv,
333-
existingEnvironmentValueSources: existingServiceCommand?.environmentValueSources,
334+
existingEnvironmentValueSources: existingManagedCommand?.environmentValueSources,
334335
warn: (message) => {
335336
if (json) {
336337
warnings.push(message);

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

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ describe("repairLoadedGatewayServiceForStart", () => {
137137
vi.unstubAllEnvs();
138138
});
139139

140-
it("drops legacy version metadata when repairing genuine service drift", async () => {
140+
it("preserves the managed base environment when an environment-only drop-in overrides it", async () => {
141141
const installMock = vi.fn(async () => {});
142142
const isLoadedMock = vi.fn(async () => true);
143143
const service = {
@@ -147,6 +147,7 @@ describe("repairLoadedGatewayServiceForStart", () => {
147147
const existingEnvironment = {
148148
HOME: "/home/openclaw",
149149
OPENCLAW_SERVICE_VERSION: "2026.4.24",
150+
OPENCLAW_WRAPPER: "/usr/bin/openclaw",
150151
TELEGRAM_DEFAULT_BOTTOKEN: "existing-env-file-token",
151152
};
152153
const existingEnvironmentValueSources = {
@@ -160,8 +161,21 @@ describe("repairLoadedGatewayServiceForStart", () => {
160161
env: {},
161162
command: {
162163
programArguments: ["/usr/bin/openclaw", "gateway", "run"],
163-
environment: existingEnvironment,
164-
environmentValueSources: existingEnvironmentValueSources,
164+
environment: {
165+
...existingEnvironment,
166+
OPENCLAW_WRAPPER: "/srv/operator/openclaw",
167+
OPERATOR_DROPIN_ONLY: "operator-owned",
168+
TELEGRAM_DEFAULT_BOTTOKEN: "operator-drop-in-token",
169+
},
170+
environmentValueSources: {
171+
...existingEnvironmentValueSources,
172+
TELEGRAM_DEFAULT_BOTTOKEN: "inline",
173+
},
174+
managedDefinition: {
175+
programArguments: ["/usr/bin/openclaw", "gateway", "run"],
176+
environment: existingEnvironment,
177+
environmentValueSources: existingEnvironmentValueSources,
178+
},
165179
},
166180
};
167181

@@ -176,6 +190,8 @@ describe("repairLoadedGatewayServiceForStart", () => {
176190
const planArg = readFirstInstallPlanArg();
177191
expect(planArg.existingEnvironment).toBe(existingEnvironment);
178192
expect(planArg.existingEnvironmentValueSources).toBe(existingEnvironmentValueSources);
193+
expect(planArg.env).not.toHaveProperty("OPERATOR_DROPIN_ONLY");
194+
expect(resolveOpenClawWrapperPathMock).toHaveBeenCalledWith("/usr/bin/openclaw");
179195
expect(installMock).toHaveBeenCalledWith(
180196
expect.objectContaining({
181197
environment: { TELEGRAM_DEFAULT_BOTTOKEN: "existing-env-file-token" },
@@ -184,6 +200,55 @@ describe("repairLoadedGatewayServiceForStart", () => {
184200
);
185201
});
186202

203+
it.each([
204+
["command", { launcher: "command" as const }, undefined],
205+
["working directory", { launcher: "working-directory" as const }, undefined],
206+
[
207+
"gateway target environment",
208+
{ environment: { keys: ["OPENCLAW_STATE_DIR"] } },
209+
{ HOME: "/home/openclaw", OPENCLAW_STATE_DIR: "/srv/operator-state" },
210+
],
211+
])(
212+
"refuses an ineffective stopped-service repair for a %s drop-in",
213+
async (_, overrides, effectiveEnvironment) => {
214+
const installMock = vi.fn(async () => {});
215+
const service = { install: installMock } as unknown as GatewayService;
216+
const managedDefinition = {
217+
programArguments: ["/usr/bin/openclaw", "gateway", "run"],
218+
workingDirectory: "/srv/openclaw",
219+
environment: { HOME: "/home/openclaw" },
220+
};
221+
const state: GatewayServiceState = {
222+
installed: true,
223+
loadState: { status: "loaded" },
224+
running: false,
225+
env: {},
226+
command: {
227+
...managedDefinition,
228+
...(effectiveEnvironment ? { environment: effectiveEnvironment } : {}),
229+
sourcePath: "/home/openclaw/.config/systemd/user/openclaw-work.service",
230+
managedDefinition,
231+
managedOverrides: overrides,
232+
},
233+
};
234+
235+
await expect(
236+
repairLoadedGatewayServiceForStart({
237+
service,
238+
state,
239+
issues: [{ code: "missing-program", message: "missing program" }],
240+
json: true,
241+
stdout: process.stdout,
242+
}),
243+
).rejects.toThrow(/systemd drop-in.*systemctl --user cat openclaw-work\.service/);
244+
245+
expect(readConfigFileSnapshotForWriteMock).not.toHaveBeenCalled();
246+
expect(resolveGatewayInstallTokenMock).not.toHaveBeenCalled();
247+
expect(buildGatewayInstallPlanMock).not.toHaveBeenCalled();
248+
expect(installMock).not.toHaveBeenCalled();
249+
},
250+
);
251+
187252
it.each(["start", "restart"] as const)(
188253
"refuses %s repair when ambient state, config, and port target a different service",
189254
async (action) => {

0 commit comments

Comments
 (0)