Skip to content

Commit 2d5228e

Browse files
fix(service): keep shell-local multishell paths out of service launchers (#6168)
* fix(service): exclude shell-local multishell launchers from service definitions Normalize and compare full launchd plists before PATH reuse, then reload changed definitions through the existing guarded lifecycle. Preserve bundled Bun and non-PATH settings; report temporary launcher repair in the present tense. Co-authored-by: Andrew <[email protected]> * Filter transient multishell PATH entries from WinSW service XML Co-authored-by: Andrew <[email protected]> --------- Co-authored-by: Andrew <[email protected]>
1 parent dce4469 commit 2d5228e

16 files changed

Lines changed: 288 additions & 17 deletions

File tree

‎docs-site/src/content/docs/getting-started/installation.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ ocx --version
4949
opencodex --version
5050
```
5151

52+
If you install the background service from a shell using fnm, nvm, mise, asdf, or volta,
53+
OpenCodex leaves shell-local multishell directories out of the service PATH. On Linux it
54+
selects a durable `ocx` launcher when available; otherwise it uses the package's Bun
55+
runtime. Run `ocx service repair` after an older service was installed from a temporary
56+
multishell directory. On macOS, repair reloads launchd when it changes the saved plist.
57+
5258
## Standalone binary (no npm)
5359

5460
Release downloads also include a standalone `ocx` binary for supported macOS, Linux, and Windows

‎docs-site/src/content/docs/reference/cli/lifecycle.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,10 @@ interrupted package update removed either file, it logs one `installation is inc
459459
stops instead of retrying the same missing executable every five seconds. Reinstall opencodex, then
460460
run `ocx service repair` to refresh the task with the restored package paths.
461461

462+
Service definitions omit shell-local version-manager multishell directories from their saved
463+
`PATH`. This includes the native Windows service installed with `ocx service install --native`;
464+
run `ocx service repair` to regenerate an older WinSW definition with a durable `PATH`.
465+
462466
On Linux, the systemd unit invokes the first regular, executable `ocx` file found on `PATH` at
463467
install time rather than the Bun and CLI paths inside the installed package tree. Version managers
464468
such as **mise** and **asdf** install into a versioned directory and delete the old one on upgrade;

‎scripts/test-layout/layout.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1544,6 +1544,7 @@
15441544
"service-tier-capability.test.ts": "service",
15451545
"service-wsl-home-ownership.test.ts": "service",
15461546
"service.test.ts": "service",
1547+
"service-multishell-path.test.ts": "service",
15471548
"session-affinity.test.ts": "server",
15481549
"session-lane-recall-harness.test.ts": "server",
15491550
"settings-desktop-switch-apply.test.ts": "config",

‎src/lib/transient-service-path.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { delimiter, posix, win32 } from "node:path";
2+
3+
/** Shell-local version-manager bins disappear when the installing shell exits. */
4+
export function isTransientServiceLauncherPath(path: string, platform: NodeJS.Platform = process.platform): boolean {
5+
const pathTools = platform === "win32" ? win32 : posix;
6+
return pathTools.normalize(path).replace(/\\/g, "/").split("/").some(component =>
7+
/^(?:asdf|fnm|mise|nvm|volta)_multishells?$/i.test(component));
8+
}
9+
10+
export function filterTransientServicePath(
11+
path: string,
12+
pathDelimiter = delimiter,
13+
platform: NodeJS.Platform = process.platform,
14+
): string {
15+
return path.split(pathDelimiter).filter(entry => !isTransientServiceLauncherPath(entry, platform)).join(pathDelimiter);
16+
}

‎src/lib/winsw.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { recordOwnedConfigPath } from "./config-ownership";
2323
import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV, durableBunRuntime } from "./bun-runtime";
2424
import type { BunRuntimeSource } from "./bun-runtime";
2525
import { serviceApiTokenFilePath } from "./service-secrets";
26+
import { filterTransientServicePath } from "./transient-service-path";
2627

2728
export const WINSW_VERSION = "2.12.0";
2829
export const WINSW_URL = `https://github.com/winsw/winsw/releases/download/v${WINSW_VERSION}/WinSW.NET461.exe`;
@@ -106,7 +107,7 @@ export function buildWinswXml(entry: WinswEntry, env: NodeJS.ProcessEnv = proces
106107
` <env name="${BUN_RUNTIME_SOURCE_ENV}" value="${xmlEscape(entry.bunRuntimeSource)}"/>`,
107108
` <env name="${BUN_RUNTIME_PATH_ENV}" value="${xmlEscape(entry.bun)}"/>`,
108109
` <env name="OCX_API_TOKEN_FILE" value="${xmlEscape(serviceApiTokenFilePath())}"/>`,
109-
` <env name="PATH" value="${xmlEscape(env.PATH ?? "")}"/>`,
110+
` <env name="PATH" value="${xmlEscape(filterTransientServicePath(env.PATH ?? "", ";", "win32"))}"/>`,
110111
env.CODEX_HOME?.trim() ? ` <env name="CODEX_HOME" value="${xmlEscape(currentCodexHomeAbsolute())}"/>` : null,
111112
env.CODEX_SQLITE_HOME?.trim() ? ` <env name="CODEX_SQLITE_HOME" value="${xmlEscape(windowsServicePathAbsolute(env.CODEX_SQLITE_HOME.trim()))}"/>` : null,
112113
` <env name="OPENCODEX_HOME" value="${xmlEscape(getConfigDir())}"/>`,

‎src/service/diagnostics.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { sh } from "./guards";
55
import { installedServiceListenPort, confirmServiceServing } from "./health";
66
import { expectedLaunchdCommand, launchdJobMatchesPlist, probeLaunchdLoadState } from "./launchd";
77
import type { LaunchdLoadProbe } from "./launchd";
8-
import { plistPath, windowsServiceScriptPath, windowsLauncherVbsPath, windowsTaskXmlPath, readServiceInstallState } from "./state";
8+
import { plistPath, windowsServiceScriptPath, windowsLauncherVbsPath, windowsTaskXmlPath, readServiceInstallState, serviceLauncherPathDiagnostic } from "./state";
99
import type { ServiceBackend } from "./state";
1010
import { unitPath, isSystemd } from "./systemd";
1111
import { statusWindowsXml } from "./windows-ops";
@@ -23,6 +23,8 @@ import { LABEL, TASK, serviceLogPath } from "./state";
2323
*/
2424
export function bakedServicePathsDiagnostic(platform: NodeJS.Platform = process.platform): string | null {
2525
const state = readServiceInstallState();
26+
const temporaryLauncher = serviceLauncherPathDiagnostic(state, platform);
27+
if (temporaryLauncher) return temporaryLauncher;
2628
// A launcher install runs the launcher, not the baked pair, so the pair's existence says
2729
// nothing about whether the service can start. Judging the recorded launcher is both
2830
// necessary (a deleted launcher IS stale) and sufficient (a replaced version directory

‎src/service/launchd.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { serviceApiTokenFilePath } from "../lib/service-secrets";
1212
import { recordOwnedConfigPath } from "../lib/config-ownership";
1313
import { writeServiceApiTokenFile, assertLiveServiceManagerAllowed } from "./guards";
1414
import { resolveServiceListenPort, buildServiceShellCommand, buildServiceLauncherShellCommand, installedServiceListenPort, resolvedProxyEnv } from "./health";
15-
import { SERVICE_MANAGED_ENV, LABEL, cliEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, type ServiceInstallState, writeServiceInstallState, readServiceInstallState } from "./state";
15+
import { SERVICE_MANAGED_ENV, LABEL, cliEntry, filterTransientServicePath, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, type ServiceInstallState, writeServiceInstallState, readServiceInstallState } from "./state";
1616
import { writeServiceDefinitionFile } from "./windows-ops";
1717
import { readTextOrNull } from "./windows-taskxml";
1818

@@ -39,7 +39,7 @@ export function buildPlist(
3939
const runtime = deps.runtime ?? durableBunRuntime();
4040
const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
4141
const log = logPath();
42-
const path = process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
42+
const path = filterTransientServicePath(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", ":", "darwin");
4343
const codexHome = process.env.CODEX_HOME?.trim();
4444
const codexSqliteHome = currentCodexSqliteHomeAbsolute();
4545
const opencodexHome = process.env.OPENCODEX_HOME?.trim();
@@ -90,6 +90,11 @@ ${envLines}
9090
*/
9191
const PLIST_PATH_ENTRY = /^(\s*<key>PATH<\/key><string>)([^\n]*)(<\/string>)$/m;
9292

93+
function filterPlistPathVariable(plist: string): string {
94+
return plist.replace(PLIST_PATH_ENTRY, (_match, open: string, value: string, close: string) =>
95+
`${open}${filterTransientServicePath(value, ":", "darwin")}${close}`);
96+
}
97+
9398
/**
9499
* The rendered plist with the PREVIOUS definition's `PATH` put back — or null when `PATH`
95100
* is not the only difference.
@@ -114,14 +119,17 @@ const PLIST_PATH_ENTRY = /^(\s*<key>PATH<\/key><string>)([^\n]*)(<\/string>)$/m;
114119
* re-install still updates it.
115120
*/
116121
export function reusePreviousPlistPathVariable(previous: string, rendered: string): string | null {
122+
if (previous === rendered) return null;
117123
const prev = PLIST_PATH_ENTRY.exec(previous);
118124
const next = PLIST_PATH_ENTRY.exec(rendered);
119-
if (!prev || !next || prev[2] === next[2]) return null;
125+
if (!prev || !next) return null;
126+
const normalizedPrevious = filterPlistPathVariable(previous);
127+
const previousPath = filterTransientServicePath(prev[2] ?? "", ":", "darwin");
120128
// A function replacer, not a `$1` template: a PATH entry containing `$&` or `$1` would
121129
// otherwise be re-expanded into the file.
122130
const adopted = rendered.replace(PLIST_PATH_ENTRY, (_match, open: string, _value: string, close: string) =>
123-
`${open}${prev[2] ?? ""}${close}`);
124-
return adopted === previous ? adopted : null;
131+
`${open}${previousPath}${close}`);
132+
return adopted === normalizedPrevious ? normalizedPrevious : null;
125133
}
126134

127135
/**

‎src/service/repair.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type { ServiceDiagnostic } from "./diagnostics";
55
import { assertServiceEnvironmentMatchesInstall, assertServiceAuthEnvironment } from "./guards";
66
import { installLaunchd, restartLaunchdJob } from "./launchd";
77
import type { LaunchdInstallOutcome } from "./launchd";
8-
import { TASK, writeServiceInstallState, serviceSourceDir, resolveServiceOwnership } from "./state";
8+
import { TASK, writeServiceInstallState, serviceSourceDir, resolveServiceOwnership, serviceLauncherPathDiagnostic } from "./state";
99
import type { ServiceOwnership, ServiceOwnershipResolution } from "./state";
1010
import { installSystemd } from "./systemd";
1111
import { writeWindowsSchedulerAssets, reregisterWindowsSchedulerTask, windowsSchedulerRegistrationMatchesSnapshot, restoreWindowsSchedulerTaskIfAbsent, startWindows, stopWindows, statusWindowsXml } from "./windows-ops";
@@ -62,6 +62,8 @@ export interface RepairServiceDeps {
6262
schedulerLauncher?: string;
6363
/** Test seam — defaults to process.platform so Linux CI cannot hit real installSystemd. */
6464
platform?: NodeJS.Platform;
65+
/** Test seam for a recorded temporary launcher. */
66+
launcherPathDiagnostic?: () => string | null;
6567
}
6668

6769
/**
@@ -175,6 +177,9 @@ export async function repairService(deps: RepairServiceDeps = {}): Promise<void>
175177
(deps.assertEnv ?? assertServiceEnvironmentMatchesInstall)();
176178
(deps.assertAuth ?? assertServiceAuthEnvironment)();
177179

180+
const temporaryLauncher = (deps.launcherPathDiagnostic ?? (() => serviceLauncherPathDiagnostic(undefined, platform, true)))();
181+
if (temporaryLauncher) console.warn(`⚠️ ${temporaryLauncher}`);
182+
178183
if (platform === "win32") {
179184
if (diag.backend === "native") {
180185
await (deps.repairNative ?? (() => installWinswService(defaultWinswEntry(serviceSourceDir))))();

‎src/service/state.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
22
import { homedir } from "node:os";
3-
import { delimiter, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
3+
import { delimiter, dirname, join, posix, resolve, win32 } from "node:path";
44
import { expandUserPath, getConfigDir } from "../config";
55
import { atomicWriteFileStreamed } from "../config/atomic-write";
66
import { resolveCodexHomeDir, type CodexHomeDeps } from "../codex/home";
77
import { resolveCodexSqliteHome } from "../codex/paths";
88
import { durableBunRuntime, type BunRuntimeSource, type DurableBunRuntime } from "../lib/bun-runtime";
99
import { WINSW_SHA256, WINSW_VERSION } from "../lib/winsw";
10+
import { isTransientServiceLauncherPath } from "../lib/transient-service-path";
11+
export { filterTransientServicePath, isTransientServiceLauncherPath } from "../lib/transient-service-path";
1012
import { isProtectedHomeUnderTest, isTestHomeGuardArmed } from "../lib/test-home-guard";
1113
import { isStandaloneBinary } from "../lib/standalone";
1214
import {
@@ -60,6 +62,18 @@ export function cliEntry(runtime: DurableBunRuntime = durableBunRuntime()): { bu
6062
};
6163
}
6264

65+
export function serviceLauncherPathDiagnostic(
66+
state: ServiceInstallState | null = readServiceInstallState(),
67+
platform: NodeJS.Platform = process.platform,
68+
repairing = false,
69+
): string | null {
70+
const launcher = state?.launcherPath;
71+
if (!launcher || !isTransientServiceLauncherPath(launcher, platform)) return null;
72+
return `STALE temporary launcher path (${launcher}) from a shell-local version manager — `
73+
+ (repairing ? "replacing it with a durable launcher or package-local Bun runtime"
74+
: "run 'ocx service repair' to replace it with a durable launcher or package-local Bun runtime");
75+
}
76+
6377
/**
6478
* The stable `ocx` launcher to bake into a systemd unit, or null to fall back to the
6579
* Bun + CLI pair.
@@ -99,8 +113,11 @@ export function stableLauncherEntry(deps: {
99113
isExecutableFile?: (path: string) => boolean;
100114
pathDelimiter?: string;
101115
state?: ServiceInstallState | null;
116+
platform?: NodeJS.Platform;
102117
} = {}): string | null {
103118
const env = deps.env ?? process.env;
119+
const platform = deps.platform ?? process.platform;
120+
const pathTools = platform === "win32" ? win32 : posix;
104121
const isExecutableFile = deps.isExecutableFile ?? ((path: string): boolean => {
105122
try {
106123
if (!statSync(path).isFile()) return false;
@@ -111,11 +128,12 @@ export function stableLauncherEntry(deps: {
111128
}
112129
});
113130
const recorded = (deps.state === undefined ? readServiceInstallState() : deps.state)?.launcherPath;
114-
if (recorded && isAbsolute(recorded) && isExecutableFile(recorded)) return recorded;
131+
if (recorded && !isTransientServiceLauncherPath(recorded, platform)
132+
&& pathTools.isAbsolute(recorded) && isExecutableFile(recorded)) return recorded;
115133
const entries = (env.PATH ?? "").split(deps.pathDelimiter ?? delimiter);
116134
for (const entry of entries) {
117-
if (!entry || !isAbsolute(entry)) continue;
118-
const candidate = join(entry, "ocx");
135+
if (!entry || isTransientServiceLauncherPath(entry, platform) || !pathTools.isAbsolute(entry)) continue;
136+
const candidate = pathTools.join(entry, "ocx");
119137
if (isExecutableFile(candidate)) return candidate;
120138
}
121139
return null;

‎src/service/systemd.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { systemdProperty } from "../service-manager-probe";
1010
import { writeServiceApiTokenFile, sh } from "./guards";
1111
import { shellQuote, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv } from "./health";
1212
import type { ServiceInstallCleanupOps } from "./orchestration";
13-
import { SERVICE_MANAGED_ENV, TASK, cliEntry, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, writeServiceInstallState } from "./state";
13+
import { SERVICE_MANAGED_ENV, TASK, cliEntry, filterTransientServicePath, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, writeServiceInstallState } from "./state";
1414
import { writeServiceDefinitionFile } from "./windows-ops";
1515

1616
/** The `--port <n>` baked into the installed systemd user unit. Linux only. */
@@ -59,7 +59,7 @@ export function buildUnit(
5959
// independent of the host PATH.
6060
const launcher = deps.launcher ?? null;
6161
const log = logPath();
62-
const path = process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
62+
const path = filterTransientServicePath(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", ":", "linux");
6363
const codexHome = systemdEnvironmentAssignment("CODEX_HOME", process.env.CODEX_HOME?.trim());
6464
const codexSqliteHome = systemdEnvironmentAssignment("CODEX_SQLITE_HOME", currentCodexSqliteHomeAbsolute());
6565
const opencodexHome = systemdEnvironmentAssignment("OPENCODEX_HOME", process.env.OPENCODEX_HOME?.trim());

0 commit comments

Comments
 (0)