Skip to content

Commit 6938f7d

Browse files
fix: allow gateway service commands for named profiles (#116314)
* fix: gateway service commands refuse a named profile or relocated OPENCLAW_HOME - Resolve the default install identity against the canonical state directory for the active OpenClaw home and profile instead of the unprofiled OS account default. - `--profile <name>` / `--dev` project `.openclaw-<profile>` state and config paths, so every named profile was classified as isolated state and refused `install`, `start`, `stop`, `restart`, `uninstall`, Doctor service repair, and self-update service handling. - `OPENCLAW_HOME` relocates all OpenClaw path defaults and is documented for running as a dedicated service user; a relocated home is now an install identity. `HOME` alone still is not. - An `OPENCLAW_STATE_DIR` or `OPENCLAW_CONFIG_PATH` pointing outside those canonical paths is still treated as isolated state. - Recovery guidance in the refusal message now names the paths that must match. Verified: focused vitest shards for the changed suites plus the daemon, CLI, and doctor suites that consume the identity check; tsgo core and core-test lanes; oxlint; docs format, MDX, link, and map checks. * fix(gateway): keep relocated homes isolated * fix(config): validate service profile identity * fix(daemon): enforce named-profile service ownership * fix(update): reject drifted service selectors before probes * test(windows): prove scheduled task lifecycle * test(windows): harden scheduled task proof cleanup * test(windows): bind lifecycle proof to checkout * test(windows): normalize cleanup exit status * test(windows): verify effective task privilege * test(windows): protect scheduled task proof roots * test(windows): prove listener-owned task lifecycle * test(windows): fix scheduled task proof contracts * test(windows): remove redundant mock coercions * test(windows): measure fallback before task probes * test(windows): prove scheduled task process origin * fix(gateway): preserve unmanaged restart fallback * test(gateway): cover denied restart ownership * test(gateway): keep restart helper types private * test(gateway): classify lifecycle helpers as test code --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent 4376387 commit 6938f7d

31 files changed

Lines changed: 2519 additions & 116 deletions

‎.github/workflows/windows-testbox-probe.yml‎

Lines changed: 160 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ on:
3838
default: false
3939
type: boolean
4040
run_windows_ci:
41-
description: "Run the focused Windows-native CI test shard after probing"
41+
description: "Run the focused Windows CI shard and native Scheduled Task proof"
4242
required: false
4343
default: false
4444
type: boolean
@@ -281,6 +281,165 @@ jobs:
281281
export PATH="$NODE_BIN:$PATH"
282282
pnpm test:windows:ci
283283
284+
- name: Preflight native Scheduled Task session
285+
if: ${{ inputs.run_windows_ci }}
286+
shell: pwsh
287+
run: |
288+
$ErrorActionPreference = "Stop"
289+
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
290+
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
291+
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
292+
$sessionId = (Get-Process -Id $PID).SessionId
293+
Write-Host "identity=$($identity.Name)"
294+
Write-Host "session_id=$sessionId"
295+
Write-Host "user_interactive=$([Environment]::UserInteractive)"
296+
Write-Host "administrator=$isAdmin"
297+
query user 2>&1 | Write-Host
298+
if (-not [Environment]::UserInteractive) {
299+
throw "Native Scheduled Task proof requires an interactive Windows runner session."
300+
}
301+
302+
- name: Run native Scheduled Task lifecycle proof
303+
id: native_schtasks
304+
if: ${{ inputs.run_windows_ci }}
305+
timeout-minutes: 5
306+
shell: bash
307+
env:
308+
CI_WINDOWS_SCHTASKS_PROOF_PATH: ${{ github.workspace }}\.artifacts\windows-schtasks\proof.json
309+
CI_WINDOWS_SCHTASKS_ROOT: ${{ runner.temp }}\openclaw-schtasks-${{ github.run_id }}-${{ github.run_attempt }}
310+
CI_WINDOWS_SCHTASKS_TEST_ID: ${{ github.run_id }}-${{ github.run_attempt }}
311+
EXPECTED_HEAD: ${{ inputs.target_ref }}
312+
run: |
313+
set -euo pipefail
314+
export PATH="$NODE_BIN:$PATH"
315+
if [[ ! "$EXPECTED_HEAD" =~ ^[0-9a-f]{40}$ ]]; then
316+
echo "Native Scheduled Task proof requires target_ref to be an exact 40-character commit SHA." >&2
317+
exit 1
318+
fi
319+
CI_WINDOWS_SCHTASKS_HEAD="$(git rev-parse HEAD)"
320+
if [[ "$CI_WINDOWS_SCHTASKS_HEAD" != "$EXPECTED_HEAD" ]]; then
321+
echo "Checked out $CI_WINDOWS_SCHTASKS_HEAD, expected frozen target $EXPECTED_HEAD." >&2
322+
exit 1
323+
fi
324+
export CI_WINDOWS_SCHTASKS_HEAD
325+
mkdir -p .artifacts/windows-schtasks
326+
pnpm test:windows:schtasks:integration
327+
328+
- name: Clean native Scheduled Task residue
329+
id: native_cleanup
330+
if: ${{ always() && inputs.run_windows_ci }}
331+
shell: pwsh
332+
env:
333+
TEST_ID: ${{ github.run_id }}-${{ github.run_attempt }}
334+
TEST_ROOT: ${{ runner.temp }}\openclaw-schtasks-${{ github.run_id }}-${{ github.run_attempt }}
335+
run: |
336+
$ErrorActionPreference = "Continue"
337+
$cleanupErrors = @()
338+
$profile = "schtasks-int-$env:TEST_ID"
339+
$taskName = "OpenClaw Gateway ($profile)"
340+
$stateDir = Join-Path $env:USERPROFILE ".openclaw-$profile"
341+
New-Item -ItemType Directory -Force -Path $env:TEST_ROOT | Out-Null
342+
schtasks.exe /End /TN $taskName 2>$null
343+
Start-Sleep -Milliseconds 200
344+
$activePidPath = Join-Path $env:TEST_ROOT "active-pid.txt"
345+
if (Test-Path -LiteralPath $activePidPath) {
346+
try {
347+
$probePid = 0
348+
$activePid = (Get-Content -LiteralPath $activePidPath -Raw).Trim()
349+
if (-not [int]::TryParse($activePid, [ref]$probePid) -or $probePid -le 1) {
350+
throw "Invalid Scheduled Task active process id: $activePid"
351+
}
352+
$processQueryError = @()
353+
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $probePid" -ErrorAction SilentlyContinue -ErrorVariable processQueryError
354+
if ($processQueryError.Count -gt 0) {
355+
throw "Could not inspect Scheduled Task probe process $probePid."
356+
}
357+
if ($process) {
358+
$probePath = Join-Path $env:TEST_ROOT "probe.cjs"
359+
$eventsPath = Join-Path $env:TEST_ROOT "runs.txt"
360+
if (
361+
$process.CommandLine -like "*$probePath*" -and
362+
$process.CommandLine -like "*$eventsPath*"
363+
) {
364+
taskkill.exe /F /T /PID $probePid 2>$null
365+
$deadline = [DateTime]::UtcNow.AddSeconds(30)
366+
do {
367+
Start-Sleep -Milliseconds 200
368+
$processQueryError = @()
369+
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $probePid" -ErrorAction SilentlyContinue -ErrorVariable processQueryError
370+
if ($processQueryError.Count -gt 0) {
371+
throw "Could not verify Scheduled Task probe process $probePid exited."
372+
}
373+
} while ($process -and [DateTime]::UtcNow -lt $deadline)
374+
if ($process) {
375+
throw "Scheduled Task probe process $probePid survived cleanup."
376+
}
377+
} else {
378+
throw "Refusing to kill reused or unverifiable process id $probePid."
379+
}
380+
}
381+
} catch {
382+
$cleanupErrors += $_.Exception.Message
383+
}
384+
}
385+
schtasks.exe /Delete /F /TN $taskName 2>$null
386+
$deleteExit = $LASTEXITCODE
387+
try {
388+
$service = New-Object -ComObject "Schedule.Service"
389+
$service.Connect()
390+
$null = $service.GetFolder("\").GetTask($taskName)
391+
$taskExists = $true
392+
} catch {
393+
$exception = $_.Exception
394+
while ($null -ne $exception.InnerException) {
395+
$exception = $exception.InnerException
396+
}
397+
if ($exception.HResult -eq -2147024894 -or $exception.HResult -eq -2147024893) {
398+
$taskExists = $false
399+
} else {
400+
$cleanupErrors += "Could not verify Scheduled Task cleanup for $taskName (HRESULT $($exception.HResult))."
401+
$taskExists = $null
402+
}
403+
}
404+
if ($taskExists -eq $true) {
405+
$cleanupErrors += "Scheduled Task cleanup left $taskName registered (delete exit $deleteExit)."
406+
}
407+
@(
408+
"task_name=$taskName"
409+
"delete_exit=$deleteExit"
410+
"task_exists=$taskExists"
411+
"proof_outcome=${{ steps.native_schtasks.outcome }}"
412+
"cleanup_errors=$($cleanupErrors -join ' ')"
413+
) | Set-Content -LiteralPath (Join-Path $env:TEST_ROOT "cleanup-summary.txt")
414+
if ($cleanupErrors.Count -gt 0) {
415+
throw ($cleanupErrors -join " ")
416+
}
417+
exit 0
418+
419+
- name: Upload native Scheduled Task proof
420+
id: native_proof_upload
421+
if: ${{ always() && inputs.run_windows_ci }}
422+
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
423+
with:
424+
name: windows-schtasks-proof-${{ github.run_id }}-${{ github.run_attempt }}
425+
path: |
426+
.artifacts/windows-schtasks/proof.json
427+
${{ runner.temp }}\openclaw-schtasks-${{ github.run_id }}-${{ github.run_attempt }}\failure-diagnostics.json
428+
${{ runner.temp }}\openclaw-schtasks-${{ github.run_id }}-${{ github.run_attempt }}\cleanup-summary.txt
429+
if-no-files-found: warn
430+
retention-days: 7
431+
432+
- name: Remove retained native Scheduled Task evidence
433+
if: ${{ always() && inputs.run_windows_ci && steps.native_cleanup.outcome == 'success' && steps.native_proof_upload.outcome == 'success' }}
434+
shell: pwsh
435+
env:
436+
TEST_ID: ${{ github.run_id }}-${{ github.run_attempt }}
437+
TEST_ROOT: ${{ runner.temp }}\openclaw-schtasks-${{ github.run_id }}-${{ github.run_attempt }}
438+
run: |
439+
$profile = "schtasks-int-$env:TEST_ID"
440+
Remove-Item -LiteralPath (Join-Path $env:USERPROFILE ".openclaw-$profile") -Recurse -Force -ErrorAction SilentlyContinue
441+
Remove-Item -LiteralPath $env:TEST_ROOT -Recurse -Force -ErrorAction SilentlyContinue
442+
284443
- name: Keep runner alive for SSH inspection
285444
if: ${{ always() && !cancelled() }}
286445
env:

‎docs/cli/gateway.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,16 @@ openclaw gateway restart --wait 30s
129129
Inline `--password` can be exposed in local process listings. Prefer `--password-file`, env, or a SecretRef-backed `gateway.auth.password`.
130130
</Warning>
131131

132+
### Install identity
133+
134+
Service management (`install`, `start`, `stop`, `restart`, `uninstall`, Doctor service repair, and self-update service handling) belongs to the install that owns the host service. That is the canonical `.openclaw` directory under the OS account home, or the `.openclaw-<profile>` directory a named profile projects there. Named profiles use distinct native service identities.
135+
136+
`OPENCLAW_HOME`, or an `OPENCLAW_STATE_DIR` or `OPENCLAW_CONFIG_PATH` that points elsewhere, is treated as isolated state and skipped. A relocated or copied state tree cannot adopt and rewrite the account's host service.
137+
138+
On macOS and Windows, native service-managed profile names must be lowercase. Runtime-only profiles may still use uppercase, but case-distinct names such as `Main` and `main` share paths on normal case-insensitive filesystems and cannot safely own separate native services. On macOS, the lowercase names `gateway` and `node` are also unavailable for native service management because their historical LaunchAgent labels collide with the default Gateway and node-host services.
139+
140+
Named profiles must also use the native service identity derived from `OPENCLAW_PROFILE`. Unset `OPENCLAW_LAUNCHD_LABEL`, `OPENCLAW_SYSTEMD_UNIT`, or `OPENCLAW_WINDOWS_TASK_NAME` before service management; custom identities remain available for the default profile or runtime-only/external-supervisor setups.
141+
132142
### External supervisors
133143

134144
Set `OPENCLAW_SUPERVISOR_MODE=external` only when another process manager owns the Gateway lifecycle. In this mode:

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1641,6 +1641,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
16411641
- H2: Run the Gateway
16421642
- H3: Options
16431643
- H2: Restart the Gateway
1644+
- H3: Install identity
16441645
- H3: External supervisors
16451646
- H3: Gateway profiling
16461647
- H2: Query a running Gateway

‎docs/help/environment.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,8 @@ unavailable instead of triggering a network request.
250250

251251
When set, `OPENCLAW_HOME` replaces the system home directory (`$HOME` / `os.homedir()`) for internal OpenClaw path defaults. This includes the default state directory, config path, agent directories, credentials, installer onboarding workspace, and the default dev checkout used by `openclaw update --channel dev`.
252252

253+
`OPENCLAW_HOME` does not grant ownership of the OS account's native Gateway service. Gateway service-management commands treat a relocated home as isolated state; use the OS account home and a named profile when a separate native service identity is required.
254+
253255
**Precedence:** `OPENCLAW_HOME` > `$HOME` > `USERPROFILE` > Termux `PREFIX` home fallback on Android > `os.homedir()`
254256

255257
**Example** (macOS LaunchDaemon):

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1894,6 +1894,7 @@
18941894
"test:voicecall:closedloop": "node scripts/test-voicecall-closedloop.mjs",
18951895
"test:watch": "node scripts/test-projects.mjs --watch",
18961896
"test:windows:ci": "node scripts/test-projects.mjs src/shared/runtime-import.test.ts src/infra/sqlite-snapshot.test.ts src/infra/ssh-client.windows.test.ts src/infra/update-managed-service-handoff.test.ts src/infra/exec-allowlist-pattern.test.ts src/infra/fs-safe-remove.test.ts src/snapshot/local-repository.windows.test.ts src/state/openclaw-database-paths.windows.test.ts src/commands/backup-verify.test.ts src/infra/state-migrations.legacy-session-store.test.ts src/test-utils/openclaw-test-state.test.ts src/agents/sessions/windows-git-bash-path.test.ts src/agents/bash-tools.exec.script-preflight.test.ts src/process/exec.windows.test.ts src/process/exec.windows.integration.test.ts src/process/windows-command.test.ts src/infra/windows-install-roots.test.ts src/node-host/invoke-system-run-allowlist.test.ts src/daemon/schtasks.startup-fallback.test.ts extensions/lobster/src/lobster-runner.test.ts extensions/mxc/test/mxc-backend.test.ts extensions/mxc/test/sandbox-policy-loader.test.ts test/e2e/qa-lab/runtime/package-openclaw-for-docker.e2e.test.ts test/scripts/format-generated-module.test.ts test/scripts/npm-runner.test.ts test/scripts/openclaw-cross-os-installer.windows.test.ts test/scripts/openclaw-cross-os-release-workflow.test.ts test/scripts/pnpm-runner.test.ts test/scripts/run-with-env.test.ts test/scripts/ts-topology.test.ts test/scripts/ui.test.ts test/scripts/vitest-process-group.test.ts",
1897+
"test:windows:schtasks:integration": "node scripts/run-with-env.mjs CI_WINDOWS_SCHTASKS_INTEGRATION=1 OPENCLAW_E2E_VERBOSE=1 OPENCLAW_VITEST_MAX_WORKERS=1 -- node scripts/run-vitest.mjs src/daemon/schtasks.integration.e2e.test.ts",
18971898
"tool-display:check": "node --import tsx scripts/tool-display.ts --check",
18981899
"tool-display:write": "node --import tsx scripts/tool-display.ts --write",
18991900
"ts-topology": "node --import tsx scripts/ts-topology.ts",

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ vi.mock("../../config/mutate.js", () => ({
104104

105105
vi.mock("../../config/paths.js", () => ({
106106
isDefaultInstallIdentity: isDefaultInstallIdentityMock,
107+
resolveNativeServiceProfileConflict: () => null,
107108
resolveGatewayPort: resolveGatewayPortMock,
108109
resolveIsNixMode: resolveIsNixModeMock,
109110
}));

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,55 @@ describe("runServiceRestart token drift", () => {
254254
);
255255
});
256256

257+
it("runs the service mutation guard before restarting a loaded service", async () => {
258+
const beforeServiceMutation = vi.fn();
259+
260+
await runServiceRestart({
261+
...createServiceRunArgs(),
262+
beforeServiceMutation,
263+
});
264+
265+
expect(beforeServiceMutation).toHaveBeenCalledTimes(1);
266+
expect(beforeServiceMutation.mock.invocationCallOrder[0]).toBeLessThan(
267+
service.restart.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
268+
);
269+
});
270+
271+
it("aborts loaded-service mutation when the service guard rejects", async () => {
272+
const repairLoadedService = vi.fn();
273+
274+
await expect(
275+
runServiceRestart({
276+
...createServiceRunArgs(),
277+
beforeServiceMutation: () => {
278+
throw new Error("service mutation denied");
279+
},
280+
repairLoadedService,
281+
}),
282+
).rejects.toThrow("service mutation denied");
283+
284+
expect(writeGatewayRestartIntentSync).not.toHaveBeenCalled();
285+
expect(repairLoadedService).not.toHaveBeenCalled();
286+
expect(service.restart).not.toHaveBeenCalled();
287+
});
288+
289+
it("does not run the service mutation guard before not-loaded recovery", async () => {
290+
service.isLoaded.mockResolvedValue(false);
291+
const beforeServiceMutation = vi.fn();
292+
293+
await runServiceRestart({
294+
...createServiceRunArgs(),
295+
beforeServiceMutation,
296+
onNotLoaded: async () => ({
297+
result: "restarted",
298+
message: "Gateway restart signal sent to unmanaged process on port 18789: 4200.",
299+
}),
300+
});
301+
302+
expect(beforeServiceMutation).not.toHaveBeenCalled();
303+
expect(service.restart).not.toHaveBeenCalled();
304+
});
305+
257306
it("repairs managed port drift before restarting", async () => {
258307
service.readRuntime.mockResolvedValue({ status: "running", pid: 1234 });
259308
service.readCommand.mockResolvedValue({

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@ export async function runServiceRestart(params: {
459459
opts?: DaemonLifecycleOptions;
460460
checkTokenDrift?: boolean;
461461
expectedPort?: number;
462+
beforeServiceMutation?: () => void;
462463
repairLoadedService?: (
463464
ctx: ServiceStartRepairContext,
464465
) => Promise<ServiceRecoveryResult<"restarted"> | null>;
@@ -533,6 +534,12 @@ export async function runServiceRestart(params: {
533534
}
534535
}
535536

537+
// Loaded services cross the native mutation boundary here. Not-loaded recovery
538+
// may still target a separately verified unmanaged listener.
539+
if (loaded) {
540+
params.beforeServiceMutation?.();
541+
}
542+
536543
if (!loaded) {
537544
try {
538545
handledRecovery = (await params.onNotLoaded?.({ json, stdout, warn, fail })) ?? null;
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
type RestartPostCheckContext = {
2+
json: boolean;
3+
stdout: NodeJS.WritableStream;
4+
warnings: string[];
5+
fail: (message: string, hints?: string[]) => void;
6+
};
7+
8+
export type RestartParams = {
9+
opts?: { json?: boolean };
10+
beforeServiceMutation?: () => void;
11+
repairLoadedService?: (ctx: {
12+
json: boolean;
13+
stdout: NodeJS.WritableStream;
14+
state: unknown;
15+
issues: unknown[];
16+
}) => Promise<unknown>;
17+
postRestartCheck?: (ctx: RestartPostCheckContext) => Promise<void>;
18+
};
19+
20+
export function requireMockCallArg(
21+
mockFn: { mock: { calls: unknown[][] } },
22+
label: string,
23+
index = 0,
24+
): Record<string, unknown> {
25+
const arg = mockFn.mock.calls[index]?.[0] as Record<string, unknown> | undefined;
26+
if (!arg) {
27+
throw new Error(`expected ${label} call #${index + 1}`);
28+
}
29+
return arg;
30+
}
31+
32+
export async function expectRestartError(
33+
promise: Promise<unknown>,
34+
): Promise<Error & { hints?: string[] }> {
35+
try {
36+
await promise;
37+
} catch (error) {
38+
return error as Error & { hints?: string[] };
39+
}
40+
throw new Error("expected restart to fail");
41+
}

0 commit comments

Comments
 (0)