Skip to content

Commit baa7394

Browse files
steipeteheyrtl
andcommitted
fix(skills): recognize binaries installed on unchanged PATH
Cache only successful binary probes so fresh skill and Gmail dependency checks recognize executables installed into existing PATH directories. Preserve hit reuse and PATH/PATHEXT invalidation; cover dependency setup, Go/uv prerequisite reuse, and skill/hook eligibility. Related: #21094. Follow-up to the positive-only proposal in #21116. Thanks to @DannyDesert for the original skill-install report. Co-authored-by: Ratul Rahman <[email protected]>
1 parent 871b18d commit baa7394

7 files changed

Lines changed: 269 additions & 21 deletions

File tree

‎docs/tools/skills.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,10 @@ metadata:
398398
At least one binary must exist on `PATH`.
399399
</ParamField>
400400

401+
Fresh dependency checks detect binaries installed into directories already on
402+
`PATH`. This does not refresh an existing session's skill snapshot; see
403+
[Snapshots and refresh](/tools/skills#snapshots-and-refresh).
404+
401405
<ParamField path="requires.env" type="string[]">
402406
Each env var must exist in the process or be provided via config.
403407
</ParamField>

‎src/hooks/config.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
13
import { describe, expect, it } from "vitest";
24
import type { OpenClawConfig } from "../config/types.openclaw.js";
5+
import { withTempDirSync } from "../test-helpers/temp-dir.js";
36
import { withEnv } from "../test-utils/env.js";
47
import { shouldIncludeHook } from "./config.js";
58
import { buildWorkspaceHookStatus } from "./hooks-status.js";
@@ -42,6 +45,24 @@ function evaluate(config?: OpenClawConfig) {
4245
return { runtimeIncluded, status };
4346
}
4447

48+
it("includes a hook after an accepted binary is installed on unchanged PATH", () => {
49+
withTempDirSync({ prefix: "openclaw-hook-binary-" }, (binDir) => {
50+
const binaryEntry: HookEntry = {
51+
...entry,
52+
metadata: { events: ["command:new"], requires: { anyBins: ["fixture-hook-tool"] } },
53+
};
54+
withEnv({ PATH: binDir }, () => {
55+
const included = () => shouldIncludeHook({ entry: binaryEntry });
56+
expect(included()).toBe(false);
57+
const executable = path.join(binDir, "fixture-hook-tool");
58+
fs.writeFileSync(executable, "#!/bin/sh\nexit 0\n");
59+
fs.chmodSync(executable, 0o755);
60+
expect(process.env.PATH).toBe(binDir);
61+
expect(included()).toBe(true);
62+
});
63+
});
64+
});
65+
4566
describe("hook environment requirements", () => {
4667
it.each([
4768
{ name: "missing values", hostEnv: undefined, configEnv: undefined, satisfied: false },

‎src/hooks/gmail-setup-utils.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5-
import { beforeEach, describe, expect, it, vi } from "vitest";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { withEnvAsync } from "../test-utils/env.js";
7+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
8+
import { withMockedPlatform } from "../test-utils/vitest-spies.js";
79
const itUnix = process.platform === "win32" ? it.skip : it;
810
const runCommandWithTimeoutMock = vi.fn();
911

@@ -20,6 +22,57 @@ async function loadGmailSetupUtils() {
2022
return await import("./gmail-setup-utils.js");
2123
}
2224

25+
describe("ensureDependency binary availability", () => {
26+
afterEach(() => runCommandWithTimeoutMock.mockReset());
27+
28+
it.each([true, false])(
29+
"checks the installed executable when installer creates it: %s",
30+
async (createsBinary) => {
31+
const { ensureDependency } = await loadGmailSetupUtils();
32+
await withOpenClawTestState({ label: "dependency-probe" }, async (state) => {
33+
const binDir = state.path("bin");
34+
await fs.mkdir(binDir);
35+
const writeExecutable = async (name: string) => {
36+
const executable = path.join(binDir, name);
37+
await fs.writeFile(executable, "#!/bin/sh\nexit 0\n");
38+
await fs.chmod(executable, 0o755);
39+
};
40+
await writeExecutable("brew");
41+
await withEnvAsync({ PATH: binDir, XDG_CONFIG_HOME: state.path("config") }, () =>
42+
withMockedPlatform("darwin", async () => {
43+
runCommandWithTimeoutMock.mockImplementation(async (argv: string[]) => {
44+
expect(argv).toEqual(["brew", "install", "fixture-probe-formula"]);
45+
if (createsBinary) {
46+
await writeExecutable("fixture-gmail-tool");
47+
}
48+
return {
49+
stdout: "",
50+
stderr: "",
51+
code: 0,
52+
signal: null,
53+
killed: false,
54+
termination: "exit",
55+
};
56+
});
57+
58+
const install = () => ensureDependency("fixture-gmail-tool", ["fixture-probe-formula"]);
59+
if (createsBinary) {
60+
await expect(install()).resolves.toBeUndefined();
61+
await expect(install()).resolves.toBeUndefined();
62+
} else {
63+
await expect(install()).rejects.toThrow(
64+
"fixture-gmail-tool still not available after brew install",
65+
);
66+
}
67+
expect(process.env.PATH).toBe(binDir);
68+
expect(runCommandWithTimeoutMock).toHaveBeenCalledTimes(1);
69+
}),
70+
);
71+
});
72+
},
73+
);
74+
});
75+
2376
describe("runGcloud interpreter resolution", () => {
2477
itUnix(
2578
"resolves a working python path and caches the result",

‎src/shared/config-eval.test.ts‎

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,21 @@
22
import fs from "node:fs";
33
import path from "node:path";
44
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { withTempDirSync } from "../test-helpers/temp-dir.js";
56
import { mockProcessPlatform } from "../test-utils/vitest-spies.js";
67
import {
78
evaluateRuntimeEligibility,
89
hasBinary,
910
isConfigPathTruthyWithDefaults,
1011
} from "./config-eval.js";
1112

12-
const originalPath = process.env.PATH;
13-
const originalPathExt = process.env.PATHEXT;
14-
1513
function setPlatform(platform: NodeJS.Platform): void {
1614
mockProcessPlatform(platform);
1715
}
1816

1917
afterEach(() => {
2018
vi.restoreAllMocks();
21-
process.env.PATH = originalPath;
22-
if (originalPathExt === undefined) {
23-
delete process.env.PATHEXT;
24-
} else {
25-
process.env.PATHEXT = originalPathExt;
26-
}
19+
vi.unstubAllEnvs();
2720
});
2821

2922
describe("config-eval helpers", () => {
@@ -108,7 +101,7 @@ describe("config-eval helpers", () => {
108101

109102
it("caches binary lookups until PATH changes", () => {
110103
setPlatform("linux");
111-
process.env.PATH = ["/missing/bin", "/found/bin"].join(path.delimiter);
104+
vi.stubEnv("PATH", ["/missing/bin", "/found/bin"].join(path.delimiter));
112105
const accessSpy = vi.spyOn(fs, "accessSync").mockImplementation((candidate) => {
113106
if (String(candidate) === path.join("/found/bin", "tool")) {
114107
return undefined;
@@ -120,7 +113,7 @@ describe("config-eval helpers", () => {
120113
expect(hasBinary("tool")).toBe(true);
121114
expect(accessSpy).toHaveBeenCalledTimes(2);
122115

123-
process.env.PATH = "/other/bin";
116+
vi.stubEnv("PATH", "/other/bin");
124117
accessSpy.mockClear();
125118
accessSpy.mockImplementation(() => {
126119
throw new Error("missing");
@@ -130,11 +123,11 @@ describe("config-eval helpers", () => {
130123
expect(accessSpy).toHaveBeenCalledTimes(1);
131124
});
132125

133-
it("checks PATHEXT candidates on Windows", () => {
126+
it("checks PATHEXT candidates and invalidates cached hits when PATHEXT changes", () => {
134127
setPlatform("win32");
135128
const toolsDir = path.join(path.sep, "tools");
136-
process.env.PATH = toolsDir;
137-
process.env.PATHEXT = ".EXE;.CMD";
129+
vi.stubEnv("PATH", toolsDir);
130+
vi.stubEnv("PATHEXT", ".EXE;.CMD");
138131
const plainCandidate = path.join(toolsDir, "tool");
139132
const exeCandidate = path.join(toolsDir, "tool.EXE");
140133
const cmdCandidate = path.join(toolsDir, "tool.CMD");
@@ -151,7 +144,36 @@ describe("config-eval helpers", () => {
151144
exeCandidate,
152145
cmdCandidate,
153146
]);
147+
148+
vi.stubEnv("PATHEXT", ".EXE");
149+
expect(hasBinary("tool")).toBe(false);
150+
vi.stubEnv("PATHEXT", ".CMD");
151+
expect(hasBinary("tool")).toBe(true);
154152
});
153+
154+
it.each([
155+
{ platform: "linux", suffix: "" },
156+
{ platform: "darwin", suffix: "" },
157+
{ platform: "win32", suffix: ".CMD" },
158+
] as const)(
159+
"finds a newly installed binary on unchanged $platform PATH",
160+
({ platform, suffix }) => {
161+
withTempDirSync({ prefix: "openclaw-binary-probe-" }, (binDir) => {
162+
setPlatform(platform);
163+
vi.stubEnv("PATH", binDir);
164+
vi.stubEnv("PATHEXT", ".EXE;.CMD");
165+
expect(hasBinary("fixture-tool")).toBe(false);
166+
167+
const executable = path.join(binDir, `fixture-tool${suffix}`);
168+
fs.writeFileSync(executable, "#!/bin/sh\nexit 0\n");
169+
fs.chmodSync(executable, 0o755);
170+
171+
expect(process.env.PATH).toBe(binDir);
172+
expect(process.env.PATHEXT).toBe(".EXE;.CMD");
173+
expect(hasBinary("fixture-tool")).toBe(true);
174+
});
175+
},
176+
);
155177
});
156178

157179
describe("runtime requirements through eligibility", () => {

‎src/shared/config-eval.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -169,21 +169,20 @@ function windowsPathExtensions(): string[] {
169169

170170
let cachedHasBinaryPath: string | undefined;
171171
let cachedHasBinaryPathExt: string | undefined;
172-
const hasBinaryCache = new Map<string, boolean>();
172+
// Installs can create binaries under unchanged PATH/PATHEXT, so cache only successful probes.
173+
const hasBinaryCache = new Set<string>();
173174

174175
/** Checks PATH for an executable binary, including PATHEXT candidates on Windows. */
175176
export function hasBinary(bin: string): boolean {
176177
const pathEnv = process.env.PATH ?? "";
177178
const pathExt = process.platform === "win32" ? (process.env.PATHEXT ?? "") : "";
178179
if (cachedHasBinaryPath !== pathEnv || cachedHasBinaryPathExt !== pathExt) {
179-
// PATH/PATHEXT changes invalidate all cached binary probes; keeping stale misses
180-
// would make newly installed tools invisible until process restart.
181180
cachedHasBinaryPath = pathEnv;
182181
cachedHasBinaryPathExt = pathExt;
183182
hasBinaryCache.clear();
184183
}
185184
if (hasBinaryCache.has(bin)) {
186-
return hasBinaryCache.get(bin)!;
185+
return true;
187186
}
188187

189188
const parts = pathEnv.split(path.delimiter).filter(Boolean);
@@ -193,13 +192,12 @@ export function hasBinary(bin: string): boolean {
193192
const candidate = path.join(part, bin + ext);
194193
try {
195194
fs.accessSync(candidate, fs.constants.X_OK);
196-
hasBinaryCache.set(bin, true);
195+
hasBinaryCache.add(bin);
197196
return true;
198197
} catch {
199198
// keep scanning
200199
}
201200
}
202201
}
203-
hasBinaryCache.set(bin, false);
204202
return false;
205203
}
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { withEnvAsync } from "../../test-utils/env.js";
6+
import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
7+
import type { SkillEntry, SkillInstallSpec } from "../types.js";
8+
import { installSkill } from "./install.js";
9+
import { skillsInstallTesting } from "./install.test-support.js";
10+
11+
const { runCommandWithTimeoutMock } = vi.hoisted(() => ({
12+
runCommandWithTimeoutMock: vi.fn<typeof import("../../process/exec.js").runCommandWithTimeout>(),
13+
}));
14+
15+
vi.mock("../../process/exec.js", () => ({
16+
runCommandWithTimeout: runCommandWithTimeoutMock,
17+
}));
18+
19+
vi.mock("../../plugins/install-security-scan.js", () => ({
20+
evaluateSkillInstallPolicy: vi.fn(async () => undefined),
21+
}));
22+
23+
afterEach(() => {
24+
skillsInstallTesting.setDepsForTest();
25+
runCommandWithTimeoutMock.mockReset();
26+
vi.restoreAllMocks();
27+
});
28+
29+
describe.each(["uv", "go"] as const)("%s bootstrap cache freshness", (kind) => {
30+
it.each([0, 1])("reuses the prerequisite after the first recipe exits %i", async (firstCode) => {
31+
await withOpenClawTestState({ label: "skill-bootstrap-probe" }, async (state) => {
32+
vi.spyOn(os, "homedir").mockReturnValue(state.home);
33+
const prefix = path.join(state.home, ".local");
34+
const binDir = path.join(prefix, "bin");
35+
await fs.mkdir(binDir, { recursive: true });
36+
const writeExecutable = async (name: string) => {
37+
const executable = path.join(binDir, name);
38+
await fs.writeFile(executable, "#!/bin/sh\nexit 0\n");
39+
await fs.chmod(executable, 0o755);
40+
};
41+
await writeExecutable("brew");
42+
43+
const entries: SkillEntry[] = ["first", "second"].map((name) => {
44+
const filePath = path.join(state.workspaceDir, name, "SKILL.md");
45+
const spec: SkillInstallSpec =
46+
kind === "uv"
47+
? { kind, package: `fixture-${name}` }
48+
: { kind, module: `example.com/fixture-${name}@latest` };
49+
return {
50+
skill: {
51+
name,
52+
description: "Binary probe fixture",
53+
filePath,
54+
baseDir: path.dirname(filePath),
55+
source: "openclaw-workspace",
56+
sourceInfo: { path: filePath, source: "test", scope: "temporary", origin: "top-level" },
57+
disableModelInvocation: false,
58+
},
59+
frontmatter: {},
60+
metadata: { install: [{ id: "deps", ...spec }] },
61+
};
62+
});
63+
skillsInstallTesting.setDepsForTest({ loadWorkspaceSkills: () => entries });
64+
65+
let bootstraps = 0;
66+
let recipes = 0;
67+
await withEnvAsync({ PATH: binDir }, async () => {
68+
runCommandWithTimeoutMock.mockImplementation(async (argv, options) => {
69+
let stdout = "";
70+
let code = 0;
71+
let stderr = "";
72+
if (argv[0] === "brew" && argv[1] === "install" && argv[2] === kind) {
73+
bootstraps += 1;
74+
await writeExecutable(kind);
75+
} else if (argv[0] === "brew" && argv[1] === "--prefix") {
76+
stdout = prefix;
77+
} else {
78+
const name = recipes === 0 ? "first" : "second";
79+
expect(argv).toEqual(
80+
kind === "uv"
81+
? ["uv", "tool", "install", `fixture-${name}`]
82+
: ["go", "install", `example.com/fixture-${name}@latest`],
83+
);
84+
await fs.access(path.join(binDir, kind), fs.constants.X_OK);
85+
if (kind === "go") {
86+
expect(options).toMatchObject({ env: { PATH: binDir, GOBIN: binDir } });
87+
}
88+
code = recipes++ === 0 ? firstCode : 0;
89+
stdout = `recipe ${name}`;
90+
stderr = code === 0 ? "" : "fixture recipe failed";
91+
}
92+
return { code, stdout, stderr, signal: null, killed: false, termination: "exit" };
93+
});
94+
95+
for (const [index, skillName] of ["first", "second"].entries()) {
96+
const code = index === 0 ? firstCode : 0;
97+
const result = await installSkill({
98+
workspaceDir: state.workspaceDir,
99+
skillName,
100+
installId: "deps",
101+
});
102+
expect(result).toMatchObject({
103+
ok: code === 0,
104+
code,
105+
stdout: `recipe ${skillName}`,
106+
stderr: code === 0 ? "" : "fixture recipe failed",
107+
});
108+
expect(process.env.PATH).toBe(binDir);
109+
}
110+
expect(recipes).toBe(2);
111+
expect(bootstraps).toBe(1);
112+
});
113+
});
114+
});
115+
});

0 commit comments

Comments
 (0)