Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(daemon): the engine's environment on Windows

Marcelitob32c783bb022
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 1f614d7..87aabc7 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -94,7 +94,7 @@ jobs:
pnpm --filter @gentle-dot/daemon run build:windows-stop -- --compiler "$compiler" --headers "$inputs/node-$version/include/node" --node-lib "$inputs/node.lib"
if ($LASTEXITCODE -ne 0) { throw 'Native addon build failed' }
- # The portable adapter tests, the real-addon refusal tests, and the agent shutdown tests.
+ # The portable adapter tests, the real-addon refusal tests, the agent shutdown tests, and the engine environment tests.
- name: Daemon tests
- run: pnpm exec vitest run packages/daemon/test/windows-stop.test.ts packages/daemon/test/windows-app-channel.test.ts packages/daemon/test/app-channel-platform.test.ts packages/daemon/test/app-channel.test.ts packages/daemon/test/app-channel-fd.test.ts packages/daemon/test/windows-app-channel-addon.test.ts packages/daemon/test/process-tree.test.ts packages/daemon/test/supervisor.test.ts
+ run: pnpm exec vitest run packages/daemon/test/windows-stop.test.ts packages/daemon/test/windows-app-channel.test.ts packages/daemon/test/app-channel-platform.test.ts packages/daemon/test/app-channel.test.ts packages/daemon/test/app-channel-fd.test.ts packages/daemon/test/windows-app-channel-addon.test.ts packages/daemon/test/process-tree.test.ts packages/daemon/test/supervisor.test.ts packages/daemon/test/runtime.test.ts packages/daemon/test/config.test.ts packages/daemon/test/isolation.test.ts
diff --git a/packages/daemon/src/config.ts b/packages/daemon/src/config.ts
index 468c564..b79e2a8 100644
--- a/packages/daemon/src/config.ts
+++ b/packages/daemon/src/config.ts
@@ -42,6 +42,37 @@ export function bundledGentleShell(env: NodeJS.ProcessEnv = process.env): string
throw new Error("The bundled assistant engine is missing. Run `pnpm install`.");
}
+/**
+ * Disable launch-time provisioning only for the installed Windows default engine.
+ * GENTLE_DOT_RUNTIME is supplied by the desktop runtime launcher; matching the
+ * executable and bundled script also leaves programmatic custom agents alone.
+ */
+export function agentSpawnEnv(
+ command: string,
+ args: string[],
+ env: NodeJS.ProcessEnv,
+ platform: NodeJS.Platform = process.platform,
+): NodeJS.ProcessEnv {
+ const runtime = runtimeDir(env);
+ if (
+ platform !== "win32" ||
+ !runtime ||
+ command !== process.execPath ||
+ env.GENTLE_DOT_AGENT_BIN ||
+ env.GENTLE_DOT_AGENT_SCRIPT ||
+ env.GENTLE_DOT_AGENT_ARGS ||
+ args[0] !== join(runtimeModules(runtime), "gentle-pi", "bin", "gentle-shell.mjs")
+ )
+ return env;
+ return {
+ ...env,
+ // gentle-shell's first-run companion provisioning gate.
+ GENTLE_SHELL_NO_AUTO_SETUP: "1",
+ // Its missing package-local gentle-ai self-heal and installer gate.
+ GENTLE_PI_SKIP_GENTLE_AI_INSTALL: "1",
+ };
+}
+
/** The web UI: the runtime's `ui/` in an installed app, the UI package's build otherwise. */
function uiDirOf(env: NodeJS.ProcessEnv): string {
const runtime = runtimeDir(env);
@@ -81,7 +112,9 @@ function parseList(value: string | undefined, name: string): string[] {
/**
* The agent is the bundled Gentle Shell by default, run with the assistant's own
* home so nothing is shared with a Gentle Shell the user may have installed.
- * GENTLE_DOT_AGENT_ARGS marks a custom agent script (tests), which gets no home.
+ * GENTLE_DOT_AGENT_SCRIPT selects an existing Gentle Shell script while keeping
+ * that separate home. GENTLE_DOT_AGENT_ARGS takes precedence for custom agent
+ * scripts (tests), which get no home.
*/
function agentConfig(env: NodeJS.ProcessEnv, dataDir: string) {
const custom = parseList(env.GENTLE_DOT_AGENT_ARGS, "GENTLE_DOT_AGENT_ARGS");
@@ -92,6 +125,12 @@ function agentConfig(env: NodeJS.ProcessEnv, dataDir: string) {
agentArgs: custom,
agentHome: undefined,
};
+ if (env.GENTLE_DOT_AGENT_SCRIPT)
+ return {
+ agentCommand: env.GENTLE_DOT_AGENT_BIN ?? process.execPath,
+ agentArgs: [env.GENTLE_DOT_AGENT_SCRIPT],
+ agentHome,
+ };
if (env.GENTLE_DOT_AGENT_BIN) return { agentCommand: env.GENTLE_DOT_AGENT_BIN, agentArgs: [], agentHome };
return { agentCommand: process.execPath, agentArgs: [bundledGentleShell(env)], agentHome };
}
diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.ts
index 682ac86..1e87a1f 100644
--- a/packages/daemon/src/isolation.ts
+++ b/packages/daemon/src/isolation.ts
@@ -12,13 +12,22 @@ import { resolveEngramBin, runtimeDir } from "./runtime.ts";
* first-run setup needs `pi` on PATH, and a clean machine has none. An installed
* app carries a relocatable `pi` in `<runtime>/bin`; pnpm's shim is not relocatable.
*/
-function bundledBinDir(base: NodeJS.ProcessEnv): string | undefined {
+interface IsolationOptions {
+ platform?: NodeJS.Platform;
+ /** Source shim directories, injectable for platform-independent tests. */
+ sourceBinDirs?: string[];
+}
+
+function bundledBinDir(base: NodeJS.ProcessEnv, options: IsolationOptions): string | undefined {
const runtime = runtimeDir(base);
if (runtime) return join(runtime, "bin");
const require = createRequire(import.meta.url);
- for (const dir of require.resolve.paths("@earendil-works/pi-coding-agent") ?? []) {
- const bin = join(dir, ".bin");
- if (existsSync(join(bin, "pi"))) return bin;
+ const bins =
+ options.sourceBinDirs ??
+ (require.resolve.paths("@earendil-works/pi-coding-agent") ?? []).map((dir) => join(dir, ".bin"));
+ const names = (options.platform ?? process.platform) === "win32" ? ["pi", "pi.cmd", "pi.exe"] : ["pi"];
+ for (const bin of bins) {
+ if (names.some((name) => existsSync(join(bin, name)))) return bin;
}
return undefined;
}
@@ -116,7 +125,7 @@ export function ensureMemoryProject(workspace: string, access: EngineAccess = di
/**
* The engine's environment: its own HOME (`<dataDir>/home`, mode 0700) with
* the XDG folders under it, because parts of the engine write to fixed places
- * under the home folder. PATH is kept, with the bundled `pi` folder first, and so is the user's git identity,
+ * under the home folder. PATH is kept (on Windows as one `PATH` key, whatever its spelling), with the bundled `pi` folder first, and so is the user's git identity,
* through `GIT_CONFIG_GLOBAL` pointing at their real `~/.gitconfig`.
*
* Memory is the user's global Engram: Engram ties a server to its data folder
@@ -140,10 +149,12 @@ export function isolatedAgentEnv(
base: NodeJS.ProcessEnv,
dataDir: string,
access: EngineAccess = directAccess,
+ options: IsolationOptions = {},
): NodeJS.ProcessEnv {
+ const platform = options.platform ?? process.platform;
const home = join(dataDir, "home");
access(() => ensurePrivateDir(home));
- const realHome = base.HOME || homedir();
+ const realHome = base.HOME || (platform === "win32" && base.USERPROFILE) || homedir();
const env: NodeJS.ProcessEnv = {
...base,
HOME: home,
@@ -153,15 +164,31 @@ export function isolatedAgentEnv(
XDG_STATE_HOME: join(home, ".local", "state"),
};
for (const key of [...INHERITED_HOMES, ...SUBAGENT_VARIABLES, ...DAEMON_ONLY]) delete env[key];
- if (!base.TMPDIR) {
+ if (platform === "win32") {
+ const tmp = join(home, ".cache", "tmp");
+ env.USERPROFILE = home;
+ env.TEMP = env.TMP = env.TMPDIR = tmp;
+ access(() => ensurePrivateDir(tmp));
+ } else if (!base.TMPDIR) {
const tmp = join(home, ".cache", "tmp");
env.TMPDIR = tmp;
access(() => ensurePrivateDir(tmp));
}
- const bin = bundledBinDir(base);
+ // Windows spells the variable `Path`, and a copy of its environment keeps that key: reading
+ // `PATH` found nothing, and a second `PATH` key beside it won, leaving the engine only the bundled
+ // folder (found by Row0902). On Windows it is read whatever its spelling and kept as one `PATH`.
+ let path = base.PATH;
+ if (platform === "win32") {
+ const keys = Object.keys(env).filter((key) => key.toUpperCase() === "PATH");
+ path = keys.map((key) => env[key]).find((value) => value !== undefined);
+ for (const key of keys) delete env[key];
+ if (path !== undefined) env.PATH = path;
+ }
+ const bin = bundledBinDir(base, options);
if (bin) {
- const rest = (base.PATH ?? "").split(delimiter).filter((part) => part && part !== bin);
- env.PATH = [bin, ...rest].join(delimiter);
+ const separator = platform === "win32" ? ";" : delimiter;
+ const rest = (path ?? "").split(separator).filter((part) => part && part !== bin);
+ env.PATH = [bin, ...rest].join(separator);
}
// The user's own Gentle Shell setting is not the assistant's.
env.GENTLE_PI_AGENTS = subagentsEnabled(base) ? "1" : "0";
@@ -174,7 +201,7 @@ export function isolatedAgentEnv(
base.GENTLE_DOT_ENGRAM_DATA_DIR || base.ENGRAM_DATA_DIR || join(realHome, ".engram");
}
const runtime = runtimeDir(base);
- if (runtime) env.ENGRAM_BIN = resolveEngramBin(base, runtime, { home: realHome });
+ if (runtime) env.ENGRAM_BIN = resolveEngramBin(base, runtime, { home: realHome, platform });
const gitConfig = join(realHome, ".gitconfig");
if (!base.GIT_CONFIG_GLOBAL && existsSync(gitConfig)) env.GIT_CONFIG_GLOBAL = gitConfig;
return env;
diff --git a/packages/daemon/src/runtime.ts b/packages/daemon/src/runtime.ts
index fb7523c..d59efb1 100644
--- a/packages/daemon/src/runtime.ts
+++ b/packages/daemon/src/runtime.ts
@@ -17,16 +17,23 @@ export function runtimeModules(runtime: string): string {
return join(runtime, "daemon", "node_modules");
}
-/** Where a user's own Engram usually lives, after the login PATH. */
-export function engramKnownDirs(home: string): string[] {
+/** Where a user's own Engram usually lives, after the login PATH on Unix. */
+export function engramKnownDirs(home: string, platform: NodeJS.Platform = process.platform): string[] {
+ if (platform === "win32") {
+ return [
+ join(home, "go", "bin"),
+ join(home, "AppData", "Local", "engram", "bin"),
+ join(home, ".local", "bin"),
+ ];
+ }
return [join(home, "go", "bin"), "/opt/homebrew/bin", "/usr/local/bin", join(home, ".local", "bin")];
}
const SYSTEM_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
-function isExecutableFile(path: string): boolean {
+function isExecutableFile(path: string, platform: NodeJS.Platform = process.platform): boolean {
try {
- accessSync(path, constants.X_OK);
+ accessSync(path, platform === "win32" ? constants.R_OK : constants.X_OK);
return statSync(path).isFile();
} catch {
return false;
@@ -54,21 +61,24 @@ function loginShellEngram(env: NodeJS.ProcessEnv, home: string): string | undefi
/**
* The Engram binary of an installed app: `ENGRAM_BIN`, then an `engram` on the
- * user's login PATH or in the usual folders, so the user's own version keeps
- * serving `~/.engram`, and only then the one the runtime carries.
+ * user's login PATH (Unix only) or in the usual folders, so the user's own version
+ * keeps serving `~/.engram`, and only then the one the runtime carries.
+ * Windows uses `engram.exe`, skips login shells and accepts readable executable files.
*/
export function resolveEngramBin(
env: NodeJS.ProcessEnv,
runtime: string,
- options: { home?: string; knownDirs?: string[] } = {},
+ options: { home?: string; knownDirs?: string[]; platform?: NodeJS.Platform } = {},
): string {
if (env.ENGRAM_BIN) return env.ENGRAM_BIN;
- const home = options.home ?? (env.HOME || homedir());
- const fromLogin = loginShellEngram(env, home);
+ const platform = options.platform ?? process.platform;
+ const home = options.home ?? (env.HOME || (platform === "win32" && env.USERPROFILE) || homedir());
+ const name = platform === "win32" ? "engram.exe" : "engram";
+ const fromLogin = platform === "win32" ? undefined : loginShellEngram(env, home);
if (fromLogin) return fromLogin;
- for (const dir of options.knownDirs ?? engramKnownDirs(home)) {
- const bin = join(dir, "engram");
- if (isExecutableFile(bin)) return bin;
+ for (const dir of options.knownDirs ?? engramKnownDirs(home, platform)) {
+ const bin = join(dir, name);
+ if (isExecutableFile(bin, platform)) return bin;
}
- return join(runtime, "bin", "engram");
+ return join(runtime, "bin", name);
}
diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.ts
index bf26761..75ea9aa 100644
--- a/packages/daemon/src/supervisor.ts
+++ b/packages/daemon/src/supervisor.ts
@@ -1,6 +1,7 @@
import { type ChildProcess, spawn } from "node:child_process";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
+import { agentSpawnEnv } from "./config.ts";
import { encodeRecord, JsonlDecoder } from "./jsonl.ts";
import { writePrivateFile } from "./private-file.ts";
import { terminateProcessTree, WINDOWS_TASKKILL_TIMEOUT_MS } from "./process-tree.ts";
@@ -326,7 +327,12 @@ export class AgentSupervisor {
const { command, args = [], extraArgs = [], cwd, env, prepareSpawn, user } = this.options;
const child = spawn(command, [...args, "--mode", "rpc", "--session-dir", this.sessionDir, ...extraArgs], {
cwd,
- env: { ...(env ?? process.env), ...prepareSpawn?.() },
+ env: agentSpawnEnv(
+ command,
+ args,
+ { ...(env ?? process.env), ...prepareSpawn?.() },
+ this.options.platform,
+ ),
stdio: ["pipe", "pipe", "pipe"],
...(user ? { uid: user.uid, gid: user.gid } : {}),
});
diff --git a/packages/daemon/test/config.test.ts b/packages/daemon/test/config.test.ts
index 91a0a9e..1c59bd6 100644
--- a/packages/daemon/test/config.test.ts
+++ b/packages/daemon/test/config.test.ts
@@ -1,9 +1,70 @@
-import { existsSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
import { describe, expect, it } from "vitest";
-import { loadConfig } from "../src/config.ts";
+import { agentSpawnEnv, bundledGentleShell, loadConfig } from "../src/config.ts";
import { tempDir } from "./helpers.ts";
+describe("packaged agent spawn environment", () => {
+ const runtime = join(process.cwd(), "packaged-runtime");
+ const script = join(runtime, "daemon", "node_modules", "gentle-pi", "bin", "gentle-shell.mjs");
+ const env = {
+ GENTLE_DOT_RUNTIME: runtime,
+ GENTLE_SHELL_NO_AUTO_SETUP: "0",
+ GENTLE_PI_SKIP_GENTLE_AI_INSTALL: "0",
+ };
+
+ it("disables both automatic setup gates for the Windows bundled default without mutating its input", () => {
+ expect(agentSpawnEnv(process.execPath, [script, "--home", "/agent"], env, "win32")).toEqual({
+ ...env,
+ GENTLE_SHELL_NO_AUTO_SETUP: "1",
+ GENTLE_PI_SKIP_GENTLE_AI_INSTALL: "1",
+ });
+ expect(env.GENTLE_SHELL_NO_AUTO_SETUP).toBe("0");
+ expect(env.GENTLE_PI_SKIP_GENTLE_AI_INSTALL).toBe("0");
+ });
+
+ it("matches the repository-local launcher's early-return gates, not just its notices", () => {
+ // Read source only: never import or execute the launcher or installer.
+ const launcherPath = bundledGentleShell({});
+ const launcher = readFileSync(launcherPath, "utf8");
+ expect(launcher).toContain('const AUTO_SETUP_OPT_OUT_ENV = "GENTLE_SHELL_NO_AUTO_SETUP";');
+ expect(launcher).toMatch(
+ /async function maybeAutoProvisionHome\([^\n]+\) \{\s*if \(process\.env\[AUTO_SETUP_OPT_OUT_ENV\] === "1"\) return undefined;/,
+ );
+ expect(launcher).toContain('const SKIP_GENTLE_AI_INSTALL_ENV = "GENTLE_PI_SKIP_GENTLE_AI_INSTALL";');
+ expect(launcher).toMatch(
+ /function ensurePackageLocalGentleAi\([^\n]+\) \{\s*if \(existsSync\(binaryPath\)\) return \{ ok: true \};\s*if \(process\.env\[SKIP_GENTLE_AI_INSTALL_ENV\] === "1"\) \{\s*return \{/,
+ );
+ const installer = readFileSync(
+ join(launcherPath, "..", "..", "scripts", "install-gentle-ai.mjs"),
+ "utf8",
+ );
+ expect(installer).toMatch(/if \(process\.env\.GENTLE_PI_SKIP_GENTLE_AI_INSTALL === "1"\) \{/);
+ });
+
+ it.each(["linux", "darwin"] as const)(
+ "preserves prior %s bundled startup and operator gate values",
+ (platform) => {
+ expect(agentSpawnEnv(process.execPath, [script], env, platform)).toEqual(env);
+ },
+ );
+
+ it("preserves Windows source and explicit launch choices", () => {
+ const cases = [
+ { command: process.execPath, args: [script], env: { ...env, GENTLE_DOT_RUNTIME: "" } },
+ { command: "custom-node", args: [script], env },
+ { command: process.execPath, args: ["external-shell.mjs"], env },
+ ...[
+ { GENTLE_DOT_AGENT_SCRIPT: script },
+ { GENTLE_DOT_AGENT_BIN: process.execPath },
+ { GENTLE_DOT_AGENT_ARGS: "[]" },
+ ].map((override) => ({ command: process.execPath, args: [script], env: { ...env, ...override } })),
+ ];
+ for (const choice of cases)
+ expect(agentSpawnEnv(choice.command, choice.args, choice.env, "win32")).toEqual(choice.env);
+ });
+});
+
describe("loadConfig", () => {
it("uses local-only defaults and the bundled Gentle Shell with the assistant's own home", () => {
const dataDir = tempDir();
@@ -19,7 +80,9 @@ describe("loadConfig", () => {
});
expect(config.preferredFolder).toBeUndefined();
expect(config.agentArgs).toHaveLength(1);
- expect(config.agentArgs[0]).toMatch(/node_modules\/gentle-pi\/bin\/gentle-shell\.mjs$/);
+ expect(config.agentArgs[0]?.endsWith(join("node_modules", "gentle-pi", "bin", "gentle-shell.mjs"))).toBe(
+ true,
+ );
expect(existsSync(config.agentArgs[0] ?? "")).toBe(true);
});
@@ -30,7 +93,29 @@ describe("loadConfig", () => {
agentArgs: [],
agentHome: join(dataDir, "agent"),
});
- expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_AGENT_HOME: "/h" }).agentHome).toBe("/h");
+ expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_AGENT_HOME: "/h" }).agentHome).toBe(
+ resolve("/h"),
+ );
+ });
+
+ it("runs an explicit Gentle Shell script with Node and keeps its separate home", () => {
+ const dataDir = tempDir();
+ const script = String.raw`C:\Users\test user\.pnpm\gentle-shell.mjs`;
+ const env = { GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_AGENT_SCRIPT: script };
+ expect(loadConfig(env)).toMatchObject({
+ agentCommand: process.execPath,
+ agentArgs: [script],
+ agentHome: join(dataDir, "agent"),
+ workspace: join(dataDir, "workspace"),
+ });
+ const home = join(dataDir, "separate-home");
+ expect(
+ loadConfig({ ...env, GENTLE_DOT_AGENT_BIN: "custom-node", GENTLE_DOT_AGENT_HOME: home }),
+ ).toMatchObject({ agentCommand: "custom-node", agentArgs: [script], agentHome: home });
+ // Empty selection preserves the existing bundled default.
+ expect(loadConfig({ ...env, GENTLE_DOT_AGENT_SCRIPT: "" })).toEqual(
+ loadConfig({ GENTLE_DOT_DATA_DIR: dataDir }),
+ );
});
it("runs a custom agent script without the Gentle Shell home", () => {
@@ -39,6 +124,7 @@ describe("loadConfig", () => {
GENTLE_DOT_DATA_DIR: dataDir,
GENTLE_DOT_AGENT_BIN: "node",
GENTLE_DOT_AGENT_ARGS: '["fake.ts"]',
+ GENTLE_DOT_AGENT_SCRIPT: "ignored-gentle-shell.mjs",
});
expect(config).toMatchObject({ agentCommand: "node", agentArgs: ["fake.ts"] });
expect(config.agentHome).toBeUndefined();
@@ -49,7 +135,7 @@ describe("loadConfig", () => {
writeFileSync(join(dataDir, "config.json"), JSON.stringify({ port: 5000, workspace: "/projects" }));
expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir })).toMatchObject({
port: 5000,
- preferredFolder: "/projects",
+ preferredFolder: resolve("/projects"),
});
expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_PORT: "6000" }).port).toBe(6000);
});
@@ -58,7 +144,10 @@ describe("loadConfig", () => {
const dataDir = tempDir();
const config = loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_WORKSPACE: "/work/repo" });
// The workspace holds the memory project setting, so the engine always works there.
- expect(config).toMatchObject({ workspace: join(dataDir, "workspace"), preferredFolder: "/work/repo" });
+ expect(config).toMatchObject({
+ workspace: join(dataDir, "workspace"),
+ preferredFolder: resolve("/work/repo"),
+ });
const same = loadConfig({
GENTLE_DOT_DATA_DIR: dataDir,
GENTLE_DOT_WORKSPACE: join(dataDir, "workspace"),
diff --git a/packages/daemon/test/isolation.test.ts b/packages/daemon/test/isolation.test.ts
index 1314862..5880d3b 100644
--- a/packages/daemon/test/isolation.test.ts
+++ b/packages/daemon/test/isolation.test.ts
@@ -7,7 +7,7 @@ import {
statSync,
writeFileSync,
} from "node:fs";
-import { join } from "node:path";
+import { delimiter, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
import {
@@ -17,21 +17,83 @@ import {
PRIVATE_ENGRAM_PORT,
} from "../src/isolation.ts";
import { FAKE_AGENT, tempDir } from "./helpers.ts";
+import { expectPosixMode } from "./support/windows.ts";
const daemons: DotDaemon[] = [];
afterEach(async () => {
await Promise.all(daemons.splice(0).map((d) => d.close()));
});
+describe("Windows isolation", () => {
+ it("isolates the OS home and Windows temp while preserving the real memory folder", () => {
+ const realHome = tempDir();
+ const data = tempDir();
+ const env = isolatedAgentEnv(
+ { USERPROFILE: realHome, TEMP: "/user/temp", TMP: "/user/tmp" },
+ data,
+ undefined,
+ {
+ platform: "win32",
+ },
+ );
+ expect(env.HOME).toBe(join(data, "home"));
+ expect(env.USERPROFILE).toBe(env.HOME);
+ expect(env.TEMP).toBe(join(data, "home", ".cache", "tmp"));
+ expect(env.TMP).toBe(env.TEMP);
+ expect(env.ENGRAM_DATA_DIR).toBe(join(realHome, ".engram"));
+ });
+
+ it("recognizes a source pi.cmd without a POSIX shim", () => {
+ const bin = tempDir();
+ writeFileSync(join(bin, "pi.cmd"), "@echo off\r\n");
+ const env = isolatedAgentEnv({ HOME: tempDir(), PATH: "/tools" }, tempDir(), undefined, {
+ platform: "win32",
+ sourceBinDirs: [bin],
+ });
+ expect(env.PATH).toBe(`${bin};/tools`);
+ });
+
+ it("keeps Unix USERPROFILE and TEMP overrides unchanged", () => {
+ const env = isolatedAgentEnv(
+ { HOME: tempDir(), USERPROFILE: "/user", TEMP: "/tmp/user", TMP: "/tmp/other" },
+ tempDir(),
+ undefined,
+ { platform: "linux" },
+ );
+ expect(env.USERPROFILE).toBe("/user");
+ expect(env.TEMP).toBe("/tmp/user");
+ expect(env.TMP).toBe("/tmp/other");
+ });
+});
+
describe("isolatedAgentEnv PATH", () => {
it("puts the bundled `pi` first so the engine's first-run setup works on a clean machine", () => {
- const env = isolatedAgentEnv({ PATH: "/usr/bin:/bin", HOME: tempDir() }, tempDir());
- const [first, ...rest] = (env.PATH ?? "").split(":");
- expect(first).toMatch(/node_modules\/\.bin$/);
- expect(existsSync(join(first ?? "", "pi"))).toBe(true);
+ const env = isolatedAgentEnv({ PATH: ["/usr/bin", "/bin"].join(delimiter), HOME: tempDir() }, tempDir());
+ const [first, ...rest] = (env.PATH ?? "").split(delimiter);
+ expect(first?.endsWith(join("node_modules", ".bin"))).toBe(true);
+ const shims = process.platform === "win32" ? ["pi", "pi.cmd", "pi.exe"] : ["pi"];
+ expect(shims.some((name) => existsSync(join(first ?? "", name)))).toBe(true);
expect(rest).toEqual(["/usr/bin", "/bin"]);
});
+ it("keeps the user's Windows Path, under one spelling, after the bundled folder (Row0902's finding)", () => {
+ // A copy of Windows' environment keeps the key as Windows spells it, `Path`. Reading `PATH`
+ // found nothing, and a second `PATH` key beside it won: the engine had only the bundled folder.
+ const bin = tempDir();
+ writeFileSync(join(bin, "pi.cmd"), "");
+ const env = isolatedAgentEnv(
+ { Path: "C:\\Windows\\System32;C:\\Git\\cmd", HOME: tempDir() },
+ tempDir(),
+ undefined,
+ {
+ platform: "win32",
+ sourceBinDirs: [bin],
+ },
+ );
+ expect(Object.keys(env).filter((key) => key.toUpperCase() === "PATH")).toEqual(["PATH"]);
+ expect(env.PATH).toBe([bin, "C:\\Windows\\System32", "C:\\Git\\cmd"].join(";"));
+ });
+
it("does not add the bundled folder twice", () => {
const once = isolatedAgentEnv({ PATH: "/bin", HOME: tempDir() }, tempDir());
const twice = isolatedAgentEnv({ PATH: once.PATH, HOME: tempDir() }, tempDir());
@@ -142,13 +204,15 @@ describe("isolatedAgentEnv temporary folder", () => {
const dataDir = tempDir();
const env = isolatedAgentEnv({ HOME: tempDir() }, dataDir);
expect(env.TMPDIR).toBe(join(dataDir, "home", ".cache", "tmp"));
- expect(statSync(env.TMPDIR ?? "").mode & 0o777).toBe(0o700);
+ expectPosixMode(statSync(env.TMPDIR ?? "").mode, 0o700);
});
- it("keeps the user's own TMPDIR", () => {
- expect(isolatedAgentEnv({ HOME: tempDir(), TMPDIR: "/var/tmp/me" }, tempDir()).TMPDIR).toBe(
- "/var/tmp/me",
- );
+ it("keeps the Unix user's own TMPDIR (Windows always isolates TEMP/TMP)", () => {
+ expect(
+ isolatedAgentEnv({ HOME: tempDir(), TMPDIR: "/var/tmp/me" }, tempDir(), undefined, {
+ platform: "linux",
+ }).TMPDIR,
+ ).toBe("/var/tmp/me");
});
});
diff --git a/packages/daemon/test/runtime.test.ts b/packages/daemon/test/runtime.test.ts
index 6964e88..0415f69 100644
--- a/packages/daemon/test/runtime.test.ts
+++ b/packages/daemon/test/runtime.test.ts
@@ -1,5 +1,5 @@
import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { delimiter, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { loadConfig } from "../src/config.ts";
@@ -7,6 +7,7 @@ import { bundledMcpCli } from "../src/connectors.ts";
import { isolatedAgentEnv } from "../src/isolation.ts";
import { resolveEngramBin } from "../src/runtime.ts";
import { tempDir } from "./helpers.ts";
+import { itWithPosixShell } from "./support/windows.ts";
const PACKAGE = fileURLToPath(new URL("..", import.meta.url));
const ENGINE_CLI = join("@earendil-works", "pi-coding-agent", "dist", "bundle", "cli.js");
@@ -44,7 +45,7 @@ describe("installed runtime (GENTLE_DOT_RUNTIME)", () => {
expect(
loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_RUNTIME: runtime, GENTLE_DOT_UI_DIR: "/ui" })
.uiDir,
- ).toBe("/ui");
+ ).toBe(resolve("/ui"));
});
it("runs the launcher and the engine's command line from the runtime's node_modules", () => {
@@ -70,13 +71,13 @@ describe("installed runtime (GENTLE_DOT_RUNTIME)", () => {
it("puts the runtime's `pi` first on the engine's PATH, never the pnpm one", () => {
const runtime = fakeRuntime();
const base = {
- PATH: "/usr/bin:/bin",
+ PATH: ["/usr/bin", "/bin"].join(delimiter),
HOME: tempDir(),
GENTLE_DOT_RUNTIME: runtime,
ENGRAM_BIN: "/x/engram",
};
const env = isolatedAgentEnv(base, tempDir());
- expect(env.PATH).toBe([join(runtime, "bin"), "/usr/bin", "/bin"].join(":"));
+ expect(env.PATH).toBe([join(runtime, "bin"), "/usr/bin", "/bin"].join(delimiter));
const again = isolatedAgentEnv({ ...base, PATH: env.PATH }, tempDir());
expect(again.PATH).toBe(env.PATH);
});
@@ -90,7 +91,7 @@ describe("installed runtime (GENTLE_DOT_RUNTIME)", () => {
expect(env).toMatchObject({ ENGRAM_BIN: "/x/engram", ENGRAM_DATA_DIR: join(realHome, ".engram") });
});
- it("finds the user's Engram through the login shell before the bundled one", () => {
+ itWithPosixShell("finds the user's Engram through the login shell before the bundled one", () => {
const runtime = fakeRuntime();
const userEngram = touch(join(tempDir(), "engram"), "", 0o755);
const env = isolatedAgentEnv(
@@ -102,25 +103,66 @@ describe("installed runtime (GENTLE_DOT_RUNTIME)", () => {
});
describe("resolveEngramBin", () => {
- it("prefers ENGRAM_BIN, then the login PATH, then the known folders, then the runtime's own", () => {
+ it("finds the Windows executable without requiring POSIX executable permissions or a login shell", () => {
+ const home = tempDir();
+ const loginEngram = touch(join(tempDir(), "engram"), "", 0o755);
+ const windowsEngram = touch(join(home, "go", "bin", "engram.exe"));
+ expect(
+ resolveEngramBin({ USERPROFILE: home, SHELL: fakeShell(loginEngram) }, fakeRuntime(), {
+ platform: "win32",
+ }),
+ ).toBe(windowsEngram);
+ });
+
+ it("finds the Windows user installation and keeps ENGRAM_BIN precedence", () => {
+ const home = tempDir();
+ const windowsEngram = touch(join(home, "AppData", "Local", "engram", "bin", "engram.exe"));
const runtime = fakeRuntime();
+ const options = { home, platform: "win32" as const };
+ expect(resolveEngramBin({}, runtime, options)).toBe(windowsEngram);
+ expect(resolveEngramBin({ ENGRAM_BIN: "/explicit/engram.exe" }, runtime, options)).toBe(
+ "/explicit/engram.exe",
+ );
+ });
+
+ it("falls back to bundled engram.exe on Windows, ignoring a login shell and non-file candidates", () => {
const home = tempDir();
- const known = tempDir();
+ mkdirSync(join(home, "go", "bin", "engram.exe"), { recursive: true });
const loginEngram = touch(join(tempDir(), "engram"), "", 0o755);
- const failing = fakeShell(undefined);
- const options = { home, knownDirs: [join(home, "missing"), known] };
- expect(resolveEngramBin({ ENGRAM_BIN: "/x/engram", SHELL: failing }, runtime, options)).toBe("/x/engram");
- expect(resolveEngramBin({ SHELL: fakeShell(loginEngram) }, runtime, options)).toBe(loginEngram);
- expect(resolveEngramBin({ SHELL: failing }, runtime, options)).toBe(join(runtime, "bin", "engram"));
- const knownEngram = touch(join(known, "engram"), "", 0o755);
- expect(resolveEngramBin({ SHELL: failing }, runtime, options)).toBe(knownEngram);
- // A login shell answer that is not an executable file is ignored.
- expect(resolveEngramBin({ SHELL: fakeShell("/nowhere/engram") }, runtime, options)).toBe(knownEngram);
+ const runtime = fakeRuntime();
+ expect(resolveEngramBin({ SHELL: fakeShell(loginEngram) }, runtime, { home, platform: "win32" })).toBe(
+ join(runtime, "bin", "engram.exe"),
+ );
});
+ itWithPosixShell(
+ "prefers ENGRAM_BIN, then the login PATH, then the known folders, then the runtime's own",
+ () => {
+ const runtime = fakeRuntime();
+ const home = tempDir();
+ const known = tempDir();
+ const loginEngram = touch(join(tempDir(), "engram"), "", 0o755);
+ const failing = fakeShell(undefined);
+ const options = { home, knownDirs: [join(home, "missing"), known] };
+ expect(resolveEngramBin({ ENGRAM_BIN: "/x/engram", SHELL: failing }, runtime, options)).toBe(
+ "/x/engram",
+ );
+ expect(resolveEngramBin({ SHELL: fakeShell(loginEngram) }, runtime, options)).toBe(loginEngram);
+ expect(resolveEngramBin({ SHELL: failing }, runtime, options)).toBe(join(runtime, "bin", "engram"));
+ const knownEngram = touch(join(known, "engram"), "", 0o755);
+ expect(resolveEngramBin({ SHELL: failing }, runtime, options)).toBe(knownEngram);
+ // A login shell answer that is not an executable file is ignored.
+ expect(resolveEngramBin({ SHELL: fakeShell("/nowhere/engram") }, runtime, options)).toBe(knownEngram);
+ },
+ );
+
it("looks in ~/go/bin, Homebrew, /usr/local/bin and ~/.local/bin by default", () => {
const home = tempDir();
- const userEngram = touch(join(home, "go", "bin", "engram"), "", 0o755);
+ const userEngram = touch(
+ join(home, "go", "bin", process.platform === "win32" ? "engram.exe" : "engram"),
+ "",
+ 0o755,
+ );
expect(resolveEngramBin({ SHELL: fakeShell(undefined) }, fakeRuntime(), { home })).toBe(userEngram);
});
});
@@ -131,8 +173,8 @@ describe("source checkout (no GENTLE_DOT_RUNTIME)", () => {
expect(config.uiDir).toBe(join(PACKAGE, "..", "ui", "dist", "app"));
expect(config.agentArgs).toEqual([join(PACKAGE, "node_modules", "gentle-pi", "bin", "gentle-shell.mjs")]);
expect(bundledMcpCli({}).args).toEqual([join(PACKAGE, "node_modules", ENGINE_CLI)]);
- const env = isolatedAgentEnv({ PATH: "/usr/bin:/bin", HOME: tempDir() }, tempDir());
- expect(env.PATH).toBe([join(PACKAGE, "node_modules", ".bin"), "/usr/bin", "/bin"].join(":"));
+ const env = isolatedAgentEnv({ PATH: ["/usr/bin", "/bin"].join(delimiter), HOME: tempDir() }, tempDir());
+ expect(env.PATH).toBe([join(PACKAGE, "node_modules", ".bin"), "/usr/bin", "/bin"].join(delimiter));
expect(env.ENGRAM_BIN).toBeUndefined();
});
});
diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.ts
index 70f3ef4..f5d9abd 100644
--- a/packages/daemon/test/supervisor.test.ts
+++ b/packages/daemon/test/supervisor.test.ts
@@ -1,3 +1,4 @@
+import * as childProcess from "node:child_process";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -5,6 +6,8 @@ import type { AgentSupervisor } from "../src/supervisor.ts";
import { fakeSupervisor, tempDir, waitFor } from "./helpers.ts";
import { itServerMode } from "./support/windows.ts";
+vi.mock("node:child_process", { spy: true });
+
const running: AgentSupervisor[] = [];
afterEach(async () => {
await Promise.all(running.splice(0).map((s) => s.stop()));
@@ -41,6 +44,33 @@ setInterval(() => {}, 1000);
`;
describe("AgentSupervisor", () => {
+ it("enforces packaged Windows setup opt-outs after prepareSpawn on every spawn without launching the engine", async () => {
+ const runtime = join(process.cwd(), "packaged-runtime");
+ const script = join(runtime, "daemon", "node_modules", "gentle-pi", "bin", "gentle-shell.mjs");
+ const spawn = vi.spyOn(childProcess, "spawn").mockImplementation(() => {
+ throw new Error("spawn intercepted");
+ });
+ try {
+ const { supervisor } = fakeSupervisor({
+ platform: "win32",
+ args: [script, "--home", "/agent"],
+ env: { GENTLE_DOT_RUNTIME: runtime, GENTLE_SHELL_NO_AUTO_SETUP: "0" },
+ prepareSpawn: () => ({ GENTLE_PI_SKIP_GENTLE_AI_INSTALL: "0", PREPARED: "yes" }),
+ });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await expect(supervisor.start()).rejects.toThrow("spawn intercepted");
+ const options = spawn.mock.calls[attempt]?.[2] as childProcess.SpawnOptions;
+ expect(options.env).toMatchObject({
+ GENTLE_SHELL_NO_AUTO_SETUP: "1",
+ GENTLE_PI_SKIP_GENTLE_AI_INSTALL: "1",
+ PREPARED: "yes",
+ });
+ }
+ } finally {
+ spawn.mockRestore();
+ }
+ });
+
it("spawns the agent in RPC mode with the session dir and extra args", async () => {
const argsFile = join(tempDir(), "argv.json");
const { supervisor, dataDir } = track(
diff --git a/packages/daemon/test/support/windows.ts b/packages/daemon/test/support/windows.ts
index af0e1d3..a52e895 100644
--- a/packages/daemon/test/support/windows.ts
+++ b/packages/daemon/test/support/windows.ts
@@ -1,4 +1,4 @@
-import { describe, it } from "vitest";
+import { describe, expect, it } from "vitest";
export const WINDOWS_APP_CHANNEL =
"Windows admits only the native production app channel (daemon.ts startDaemon); the protocol is covered on Linux and macOS";
@@ -9,18 +9,32 @@ export const INHERITED_APP_CHANNEL =
export const SERVER_MODE =
"Server mode runs the engine as another POSIX user (setuid); it is Linux only and covered on Linux";
+export const POSIX_FILE_MODE =
+ "Windows has no POSIX permission bits; private files rely on the user profile's ACL. Linux and macOS cover these mode assertions";
+
+export const POSIX_LOGIN_SHELL =
+ "Windows intentionally ignores POSIX login shells; Linux and macOS cover login-shell Engram discovery";
+
const windows = process.platform === "win32";
+/** Keep the test and its stat/lstat running; only POSIX permission bits are platform-specific. */
+export function expectPosixMode(actualMode: number, expectedMode: number): void {
+ if (!windows) expect(actualMode & 0o777, POSIX_FILE_MODE).toBe(expectedMode);
+}
+
/** Only daemon tests requiring a generic Duplex app channel lack Windows coverage. */
export const describeWithAppChannel: ReturnType<typeof describe.skipIf> = describe.skipIf(windows);
/** Server-mode tests are absent on Windows; desktop and generic file behavior remain active. */
export const itServerMode: ReturnType<typeof it.skipIf> = it.skipIf(windows);
+export const itWithPosixShell: ReturnType<typeof it.skipIf> = it.skipIf(windows);
+
export const describeWithInheritedAppChannel: ReturnType<typeof describe.skipIf> = describe.skipIf(windows);
if (windows) {
console.info(`Windows-only test skip: ${WINDOWS_APP_CHANNEL}`);
console.info(`Windows-only test skip: ${SERVER_MODE}`);
console.info(`Windows-only test skip: ${INHERITED_APP_CHANNEL}`);
+ console.info(`Windows-only test skip: ${POSIX_LOGIN_SHELL}`);
}