fix(setup): follow and validate Hermes sticky profiles (#1528)

* fix: follow Hermes sticky profile for setup paths

* test: cover Hermes sticky profile paths

* fix: honor Hermes profiles with home overrides

* style: format Hermes profile lookup

* style: format Hermes profile tests

* fix(ci): avoid load-sensitive escape regression timing

* fix(setup): validate Hermes sticky profile identity

---------

Co-authored-by: N0zoM1z0 <1705004398@qq.com>
This commit is contained in:
Peter
2026-10-10 18:19:51 +08:00
committed by GitHub
co-authored by N0zoM1z0
parent 92741187ec
commit 86b223b33e
6 changed files with 394 additions and 56 deletions
+5
View File
@@ -208,6 +208,11 @@ Windows, `~/.hermes` elsewhere — including any `HERMES_DATA_DIR_SUFFIX`. Herme
connects an entry unless `enabled` is false, so setup states `enabled: true`.
Hermes personal skills install under the active Hermes home's `skills` directory.
Setup, doctor and uninstall follow the root's `active_profile` selection, as
plain Hermes CLI commands do. An explicit `HERMES_HOME` pointing to
`profiles/<name>` selects that named profile directly. An invalid, missing or
deleted sticky profile is reported instead of writing into the default home;
repair the profile or run `hermes profile use default` before retrying.
REA follows `HERMES_HOME` whitespace trimming, environment-variable expansion,
and home expansion before resolving that profile. Setup previews the resolved
configuration and skill destinations; doctor and uninstall use those same paths.
+2
View File
@@ -102,6 +102,8 @@ cleanup. These POSIX lanes use a deterministic loopback model, so they do not
prove live model-provider or native Windows compatibility. Qwen and Pi use
caller-configured skill directories to isolate the fixture account from the OS
home; this does not prove their default home-directory discovery.
Set `REA_VERIFY_HERMES_STICKY_PROFILE=1` to exercise native Hermes selection of
a named sticky profile with `HERMES_HOME` still pointing to its root.
Full E2E tests invoke the production command dispatcher and real providers,
without fake launchers, runners or responses. `verify:keyed-archive` writes an
+14 -3
View File
@@ -27,11 +27,16 @@ const command =
const lab = await mkdtemp(join(tmpdir(), `rea-${client}-client-`));
const account = join(lab, "account");
const profile = join(lab, "selected profile");
const stickyHermes =
client === "hermes" && process.env.REA_VERIFY_HERMES_STICKY_PROFILE === "1";
const selectedProfile = stickyHermes
? join(profile, "profiles", "coder")
: profile;
const workspace = join(lab, "workspace");
const target = join(workspace, "fixture α测试");
const artifactPath = join(workspace, "evidence.json");
const skillPath = join(
client === "pi" ? join(account, ".agents") : profile,
client === "pi" ? join(account, ".agents") : selectedProfile,
"skills",
"reverse-engineer-anything",
"SKILL.md",
@@ -39,7 +44,8 @@ const skillPath = join(
const verifier = createVerifierRun();
await Promise.all([
mkdir(account),
mkdir(profile),
mkdir(profile, { recursive: true }),
...(stickyHermes ? [mkdir(selectedProfile, { recursive: true })] : []),
mkdir(target, { recursive: true }),
]);
await writeFile(
@@ -53,7 +59,11 @@ const environment = {
PI_OFFLINE: "1",
REA_PROCESS_RUN_ID: verifier.run_id,
};
const configPath = join(profile, client === "pi" ? "mcp.json" : "config.yaml");
const configPath = join(
selectedProfile,
client === "pi" ? "mcp.json" : "config.yaml",
);
if (stickyHermes) await writeFile(join(profile, "active_profile"), "coder\n");
const original =
client === "pi"
? JSON.stringify({
@@ -440,6 +450,7 @@ try {
client === "pi"
? "caller-configured isolated shared directory; default OS home discovery unverified"
: "native HERMES_HOME personal directory",
stickyHermes,
catalogSize: catalog?.length,
evidenceSeen,
skillLoaded,
+150
View File
@@ -0,0 +1,150 @@
import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
import {
basename,
dirname,
isAbsolute,
join,
relative,
resolve,
sep,
} from "node:path";
/** An unresolved Hermes profile must not be configured as the default home. */
export class HermesClientPathError extends Error {
constructor(
readonly path: string,
message: string,
) {
super(message);
this.name = "HermesClientPathError";
}
}
const defaultDirectory = (
home: string,
platform: NodeJS.Platform,
env: Readonly<NodeJS.ProcessEnv>,
): string => {
const suffix = env.HERMES_DATA_DIR_SUFFIX ?? "";
return platform === "win32"
? join(
env.LOCALAPPDATA?.trim() || join(home, "AppData", "Local"),
`hermes${suffix}`,
)
: join(home, `.hermes${suffix}`);
};
const expandedDirectory = (
home: string,
platform: NodeJS.Platform,
env: Readonly<NodeJS.ProcessEnv>,
): string | undefined => {
const override = env.HERMES_HOME?.trim();
if (!override) return undefined;
const variables = override.replace(
/\$(\w+|\{[^}]*\})/gu,
(match, variable: string) => {
const key = variable.startsWith("{") ? variable.slice(1, -1) : variable;
return env[key] ?? match;
},
);
const expanded =
platform === "win32"
? variables.replace(
/%([^%]+)%/gu,
(match, variable: string) => env[variable] ?? match,
)
: variables;
if (expanded === "~") return home;
if (
expanded.startsWith("~/") ||
(platform === "win32" && expanded.startsWith("~\\"))
)
return join(home, expanded.slice(2));
return resolve(expanded);
};
const physicalPath = (path: string): string => {
try {
return realpathSync(path);
} catch {
return resolve(path);
}
};
const within = (root: string, path: string): boolean => {
const difference = relative(physicalPath(root), physicalPath(path));
return (
difference === "" ||
(!isAbsolute(difference) &&
difference !== ".." &&
!difference.startsWith(`..${sep}`))
);
};
const PROFILE_MARKERS = [
"config.yaml",
".env",
"SOUL.md",
"profile.yaml",
"auth.json",
"state.db",
];
const RESERVED_PROFILES = new Set(["hermes", "test", "tmp", "root", "sudo"]);
const liveProfile = (path: string): boolean => {
try {
if (!statSync(path).isDirectory()) return false;
try {
statSync(join(dirname(path), ".deleted", basename(path)));
return false;
} catch {
/* No tombstone. */
}
return PROFILE_MARKERS.some((marker) => {
try {
const status = lstatSync(join(path, marker));
return status.isFile() || status.isSymbolicLink();
} catch {
return false;
}
});
} catch {
return false;
}
};
/** Match Hermes CLI sticky-profile selection while retaining the configured path spelling. */
export const resolveHermesClientHome = (
home: string,
platform: NodeJS.Platform,
env: Readonly<NodeJS.ProcessEnv>,
): string => {
const native = defaultDirectory(home, platform, env);
const root = expandedDirectory(home, platform, env) ?? native;
// An explicit named profile bypasses the root's sticky selection in Hermes CLI.
if (basename(dirname(root)) === "profiles") return root;
const stickyRoot = within(native, root) ? native : root;
let name: string;
try {
// Python uses utf-8-sig and ignores unreadable / invalid-UTF8 active_profile files.
name = new TextDecoder("utf-8", { fatal: true })
.decode(readFileSync(join(stickyRoot, "active_profile")))
.trim();
} catch {
return root;
}
if (name === "" || name === "default") return root;
const canonical = name.toLowerCase();
if (canonical === "default") return root;
if (
!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(canonical) ||
RESERVED_PROFILES.has(canonical)
)
throw new HermesClientPathError(
join(stickyRoot, "active_profile"),
`Invalid saved Hermes profile ${JSON.stringify(name)}. Run 'hermes profile use default' or repair active_profile.`,
);
const selected = join(root, "profiles", canonical);
if (!liveProfile(selected))
throw new HermesClientPathError(
selected,
`Saved Hermes profile ${JSON.stringify(name)} is missing, deleted, or has no profile identity. Run 'hermes profile use default' or restore that profile before configuring it.`,
);
return selected;
};
+29 -51
View File
@@ -1,6 +1,10 @@
import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { lstatSync } from "node:fs";
import {
HermesClientPathError,
resolveHermesClientHome,
} from "./HermesClientHome.js";
/** One supported client configuration location. */
export interface SetupClient {
@@ -115,49 +119,8 @@ const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
const grokDirectory = ({ home, env }: ClientPathContext): string =>
env.GROK_HOME || join(home, ".grok");
/**
* Hermes Agent home. `HERMES_HOME` wins; otherwise the platform default mirrors
* Hermes's own resolver (`%LOCALAPPDATA%\\hermes` on Windows, `~/.hermes`
* elsewhere), including the optional `HERMES_DATA_DIR_SUFFIX` that is appended
* to the literal `hermes`/`.hermes` directory name.
*/
const hermesDirectory = ({
home,
platform,
env,
}: ClientPathContext): string => {
const override = env.HERMES_HOME?.trim();
if (override) {
const expandedVariables = override.replace(
/\$(\w+|\{[^}]*\})/gu,
(match, variable: string) => {
const key = variable.startsWith("{") ? variable.slice(1, -1) : variable;
return env[key] ?? match;
},
);
const expanded =
platform === "win32"
? expandedVariables.replace(
/%([^%]+)%/gu,
(match, variable: string) => env[variable] ?? match,
)
: expandedVariables;
if (expanded === "~") return home;
if (
expanded.startsWith("~/") ||
(platform === "win32" && expanded.startsWith("~\\"))
)
return join(home, expanded.slice(2));
return resolve(expanded);
}
const suffix = env.HERMES_DATA_DIR_SUFFIX ?? "";
return platform === "win32"
? join(
env.LOCALAPPDATA?.trim() || join(home, "AppData", "Local"),
`hermes${suffix}`,
)
: join(home, `.hermes${suffix}`);
};
const hermesDirectory = ({ home, platform, env }: ClientPathContext): string =>
resolveHermesClientHome(home, platform, env);
/** Grok Bot uses an absolute SAND_DATA_ROOT; anything else stays ~/.grokbot. */
const grokBotDirectory = ({ home, env }: ClientPathContext): string => {
@@ -577,6 +540,14 @@ export const supportedClients = (
format: definition.format,
};
} catch (cause: unknown) {
if (cause instanceof HermesClientPathError)
return {
name: definition.name,
displayName: definition.displayName,
format: definition.format,
configPath: cause.path,
configPathError: cause.message,
};
if (definition.name !== "pi") throw cause;
return {
name: definition.name,
@@ -611,14 +582,21 @@ export const clientSkillDirectories = (
const destinations = new Map<string, { client: string; directory: string }>();
for (const client of selected) {
const definition = definitions.find(({ name }) => name === client);
const directory =
definition?.skillPath === undefined
? join(home, ".agents", "skills")
: resolvePath(definition.skillPath, {
home,
platform,
env: environment,
});
let directory: string;
try {
directory =
definition?.skillPath === undefined
? join(home, ".agents", "skills")
: resolvePath(definition.skillPath, {
home,
platform,
env: environment,
});
} catch (cause: unknown) {
// Registration diagnostics own an unresolved profile; never fall back to another skill root.
if (cause instanceof HermesClientPathError) continue;
throw cause;
}
if (!destinations.has(directory))
destinations.set(directory, {
client:
@@ -22,9 +22,9 @@ cliTest(
arguments: arguments_,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
HERMES_HOME: " ${HOME}/profile ",
REA_CLIENT_PROFILE_HOME: home,
HERMES_HOME: " ${REA_CLIENT_PROFILE_HOME}/profile ",
},
timeoutMs: 20_000,
});
@@ -96,3 +96,195 @@ cliTest(
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
},
);
for (const selection of ["default", "custom", "suffix", "explicit"] as const) {
cliTest(
`Hermes ${selection} sticky-profile selection preserves the root configuration`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-hermes-sticky-");
const suffix = selection === "suffix" ? "-dev" : "";
const native =
process.platform === "win32"
? join(home, "AppData", "Local", `hermes${suffix}`)
: join(home, `.hermes${suffix}`);
const root = selection === "custom" ? join(home, "custom root") : native;
const profile = join(
root,
"profiles",
selection === "explicit" ? "other" : "coder",
);
await mkdir(profile, { recursive: true });
const original =
"# profile settings\nmodel: custom\nmcp_servers:\n other:\n command: other-server\n";
const config = join(profile, "config.yaml");
const rootConfig = join(root, "config.yaml");
await writeFile(config, original);
await writeFile(rootConfig, "model: root-model\n");
await writeFile(join(root, "active_profile"), "\uFEFFCoDeR\r\n");
const run = (args: readonly string[]) =>
cli.run({
arguments: args,
cwd: home,
environment: {
USERPROFILE: home,
LOCALAPPDATA: join(home, "AppData", "Local"),
HERMES_DATA_DIR_SUFFIX: suffix,
HERMES_HOME:
selection === "explicit"
? profile
: selection === "custom"
? root
: undefined,
},
timeoutMs: 20_000,
});
const plan = await run([
"setup",
"--client",
"hermes",
"--dry-run",
"--json",
]);
expect(plan.exitCode).toBe(0);
expect(plan.json).toMatchObject({
status: "planned",
plannedActions: expect.arrayContaining([
expect.objectContaining({ target: config }),
expect.objectContaining({
target: join(profile, "skills", "reverse-engineer-anything"),
}),
]),
});
expect(
(await run(["setup", "--client", "hermes", "--yes", "--json"]))
.exitCode,
).toBe(0);
expect(parse(await readFile(config, "utf8"))).toMatchObject({
mcp_servers: {
rea: { enabled: true },
other: { command: "other-server" },
},
});
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
const skill = join(
profile,
"skills",
"reverse-engineer-anything",
"SKILL.md",
);
expect(await readFile(skill, "utf8")).toContain(
"name: reverse-engineer-anything",
);
if (selection === "custom") {
const doctor = await run([
"doctor",
"--client",
"hermes",
"--skill",
"--json",
]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: {
skill: { state: "aligned" },
registrations: expect.arrayContaining([
expect.objectContaining({
client: "hermes",
config_path: config,
state: "aligned",
}),
]),
},
});
expect(
(await run(["setup", "--client", "hermes", "--yes", "--json"])).json,
).toMatchObject({ appliedActions: [] });
expect((await run(["uninstall", "--json"])).exitCode).toBe(0);
expect(parse(await readFile(config, "utf8"))).toEqual(parse(original));
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
}
expect(await readFile(rootConfig, "utf8")).toBe("model: root-model\n");
await expect(access(`${rootConfig}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
await expect(
access(join(root, "skills", "reverse-engineer-anything")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
}
for (const name of ["missing", "deleted", "ghost", "../escape", "root"]) {
cliTest(
`Hermes rejects unusable sticky profile ${name} without writing a fallback home`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-hermes-invalid-profile-");
const root = join(home, "hermes root");
await mkdir(root);
await writeFile(join(root, "active_profile"), name);
if (name === "deleted" || name === "ghost") {
await mkdir(join(root, "profiles", name), { recursive: true });
if (name === "deleted") {
await writeFile(
join(root, "profiles", name, "config.yaml"),
"model: custom\n",
);
await mkdir(join(root, "profiles", ".deleted"));
await writeFile(
join(root, "profiles", ".deleted", name),
"deleted\n",
);
}
}
const run = (args: readonly string[]) =>
cli.run({
arguments: args,
cwd: home,
environment: { USERPROFILE: home, HERMES_HOME: root },
timeoutMs: 20_000,
});
const rejected = await run([
"setup",
"--client",
"hermes",
"--yes",
"--json",
]);
expect(rejected.exitCode).not.toBe(0);
expect(rejected.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("Hermes profile"),
});
await expect(access(join(root, "config.yaml"))).rejects.toMatchObject({
code: "ENOENT",
});
await expect(access(join(root, "skills"))).rejects.toMatchObject({
code: "ENOENT",
});
if (name !== "missing") return;
const doctor = await run(["doctor", "--client", "hermes", "--json"]);
expect(doctor.exitCode).not.toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "hermes",
state: "invalid",
remediation: expect.stringContaining("Hermes profile"),
}),
]),
},
});
const unrelated = await run([
"setup",
"--client",
"codex",
"--yes",
"--json",
]);
expect(unrelated.exitCode).toBe(0);
},
);
}