Skip to content

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

TypeScript

feat(package): stage the Windows runtime with an isolated install

Marcelitofc6d81d67ed8
diff --git a/scripts/package/lib.mjs b/scripts/package/lib.mjs
index e9bb18d..14e7950 100644
--- a/scripts/package/lib.mjs
+++ b/scripts/package/lib.mjs
@@ -1,7 +1,8 @@
// Pure helpers for staging the installed app's runtime (`stage-runtime.mjs`).
+import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
-import { createReadStream, lstatSync, readdirSync, renameSync } from "node:fs";
-import { join } from "node:path";
+import { createReadStream, existsSync, lstatSync, readdirSync, renameSync } from "node:fs";
+import { join, posix, win32 } from "node:path";
/**
* The targets a runtime can be staged for, with the names Node's and Engram's
@@ -140,6 +141,79 @@ export function renameWhenReleased(
}
}
+/** Explicit build prerequisite only; never search or inherit the user's entire PATH. */
+export function windowsBuildGo(source, isFile) {
+ const exe = source.GENTLE_DOT_BUILD_GO;
+ if (
+ !exe ||
+ !win32.isAbsolute(exe) ||
+ win32.basename(exe).toLowerCase() !== "go.exe" ||
+ /[;\r\n"]/.test(exe)
+ )
+ throw new Error("GENTLE_DOT_BUILD_GO must name an absolute, already provisioned go.exe.");
+ if (!isFile(exe)) throw new Error("GENTLE_DOT_BUILD_GO must name an existing regular file.");
+ return exe;
+}
+
+/** Windows builds have module/binary provenance, not a downloaded archive checksum. */
+export function gentleAiIntegritySummary(info) {
+ if (info.method === "go-sumdb-source-build")
+ return `gentle-ai ${info.version} via ${info.method} ${info.package}@${info.tag} (module checksum ${info.moduleChecksum}; binary sha256 ${info.binarySha256}; Go ${info.goVersion})`;
+ return `gentle-ai ${info.version} from ${info.asset} (sha256 ${info.assetSha256})`;
+}
+
+/** Child-only environment: installers do not inherit the user's home or credentials. */
+export function installerEnv(out, cache, target, source = process.env, goExecutable) {
+ const windows = target === "windows-x64";
+ const path = windows ? win32.join : posix.join;
+ const home = path(cache, "npm-home");
+ const env = {
+ HOME: home,
+ PATH: `${path(out, "node", "bin")}:/usr/bin:/bin:/usr/sbin:/sbin`,
+ TMPDIR: source.TMPDIR ?? "/tmp",
+ npm_config_userconfig: path(cache, "npmrc"),
+ npm_config_cache: path(cache, "npm-cache"),
+ npm_config_registry: "https://registry.npmjs.org/",
+ npm_config_update_notifier: "false",
+ };
+ if (windows) {
+ const get = (key) =>
+ Object.entries(source).find(([name]) => name.toLowerCase() === key.toLowerCase())?.[1];
+ const root = get("SystemRoot");
+ if (!root) throw new Error("Windows installers require SystemRoot.");
+ delete env.TMPDIR;
+ Object.assign(env, {
+ USERPROFILE: home,
+ LOCALAPPDATA: path(home, "AppData", "Local"),
+ APPDATA: path(home, "AppData", "Roaming"),
+ SystemRoot: root,
+ ComSpec: path(root, "System32", "cmd.exe"),
+ PATH: [
+ path(out, "node", "bin"),
+ path(root, "System32"),
+ root,
+ ...(goExecutable ? [win32.dirname(goExecutable)] : []),
+ ].join(";"),
+ TEMP: get("TEMP") ?? get("TMP") ?? path(home, "Temp"),
+ TMP: get("TMP") ?? get("TEMP") ?? path(home, "Temp"),
+ });
+ }
+ return env;
+}
+
+/** No shell quoting or direct .cmd spawn: pnpm supplies its JS entry via npm_execpath. */
+export function pnpmInvocation(
+ args,
+ platform = process.platform,
+ env = process.env,
+ node = process.execPath,
+) {
+ if (platform !== "win32") return { command: "pnpm", args };
+ if (!/pnpm\.(?:c?js|mjs)$/i.test(env.npm_execpath ?? ""))
+ throw new Error("Run Windows staging through pnpm so npm_execpath names pnpm's JavaScript entry.");
+ return { command: node, args: [env.npm_execpath, ...args] };
+}
+
/** The SHA-256 a `SHASUMS256.txt` / `checksums.txt` listing gives `fileName`; throws when it is absent. */
export function checksumFor(listing, fileName) {
for (const line of listing.split("\n")) {
@@ -206,6 +280,19 @@ export function formatSize(bytes) {
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
+/** A copied Windows source tree has no Git revision; never manufacture one. */
+export function daemonSourceRevision(
+ repo,
+ platform = process.platform,
+ present = existsSync,
+ git = execFileSync,
+) {
+ if (platform === "win32" && !present(join(repo, ".git"))) return "snapshot-unversioned";
+ const commit = git("git", ["rev-parse", "HEAD"], { cwd: repo, encoding: "utf8" }).trim();
+ const dirty = git("git", ["status", "--porcelain", "--", "packages"], { cwd: repo, encoding: "utf8" });
+ return dirty.trim() ? `${commit}-dirty` : commit;
+}
+
/** The runtime's `MANIFEST.json` content. */
export function buildManifest({ target, versions, daemonCommit, sizeBytes, stagedAt }) {
for (const key of ["node", "engram", "gentlePi"])
diff --git a/scripts/package/stage-runtime.mjs b/scripts/package/stage-runtime.mjs
index b8e97bc..9f23bac 100644
--- a/scripts/package/stage-runtime.mjs
+++ b/scripts/package/stage-runtime.mjs
@@ -26,25 +26,29 @@ import {
assertHostTarget,
buildManifest,
checksumFor,
+ daemonSourceRevision,
engramArchiveName,
engramReleaseVersion,
formatSize,
+ gentleAiIntegritySummary,
+ installerEnv,
nodeArchiveName,
nodeExtractionPlan,
nodeVersion,
npmWrapper,
parseArgs,
+ pnpmInvocation,
renameWhenReleased,
symlinksIn,
treeSize,
verifyChecksum,
versionFromReleaseUrl,
+ windowsBuildGo,
} from "./lib.mjs";
const REPO = fileURLToPath(new URL("../..", import.meta.url));
const CACHE = join(REPO, ".cache", "package");
const ENGRAM_RELEASES = "https://github.com/Gentleman-Programming/engram/releases";
-const SYSTEM_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
const say = (line) => process.stdout.write(`${line}\n`);
@@ -153,7 +157,7 @@ function openGentleAi(daemon) {
return integrity;
}
-function installDaemonModules(out) {
+function installDaemonModules(out, target, goExecutable) {
const daemon = join(out, "daemon");
const npmHome = join(CACHE, "npm-home");
mkdirSync(npmHome, { recursive: true });
@@ -161,8 +165,12 @@ function installDaemonModules(out) {
writeFileSync(npmrc, "");
say("Daemon dependencies (npm install --omit=dev)");
// A clean npm setup: no user npmrc, a cache of its own, and a scratch HOME for install scripts.
+ const env = installerEnv(out, CACHE, target, process.env, goExecutable);
+ if (target === "windows-x64")
+ for (const path of [env.LOCALAPPDATA, env.APPDATA, env.TEMP, env.TMP])
+ mkdirSync(path, { recursive: true });
const result = spawnSync(
- join(out, "node", "bin", "node"),
+ join(out, "node", "bin", target === "windows-x64" ? "node.exe" : "node"),
[
join(out, "node", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
"install",
@@ -176,15 +184,7 @@ function installDaemonModules(out) {
cwd: daemon,
encoding: "utf8",
maxBuffer: 64 * 1024 * 1024,
- env: {
- HOME: npmHome,
- PATH: `${join(out, "node", "bin")}:${SYSTEM_PATH}`,
- TMPDIR: process.env.TMPDIR ?? "/tmp",
- npm_config_userconfig: npmrc,
- npm_config_cache: join(CACHE, "npm-cache"),
- npm_config_registry: "https://registry.npmjs.org/",
- npm_config_update_notifier: "false",
- },
+ env,
},
);
process.stdout.write(result.stdout ?? "");
@@ -195,7 +195,7 @@ function installDaemonModules(out) {
.filter((line) => /Gentle AI|gentle-pi/.test(line) && !/^>/.test(line.trim()));
const gentleAi = openGentleAi(daemon);
say(` gentle-pi postinstall: ${postinstall.join(" | ") || "(no output)"}`);
- say(` gentle-ai ${gentleAi.version} from ${gentleAi.asset} (sha256 ${gentleAi.assetSha256})`);
+ say(` ${gentleAiIntegritySummary(gentleAi)}`);
const pkg = (name) =>
JSON.parse(readFileSync(join(daemon, "node_modules", name, "package.json"), "utf8")).version;
return {
@@ -247,21 +247,25 @@ async function stageEngram(out, target, requested) {
}
function daemonCommit() {
- const commit = execFileSync("git", ["rev-parse", "HEAD"], { cwd: REPO, encoding: "utf8" }).trim();
- const dirty = execFileSync("git", ["status", "--porcelain", "--", "packages"], {
- cwd: REPO,
- encoding: "utf8",
- });
- return dirty.trim() ? `${commit}-dirty` : commit;
+ return daemonSourceRevision(REPO);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const { target } = options;
assertHostTarget(target);
- // The Windows downloads are in place; its isolated dependency install is not yet.
- if (target === "windows-x64")
- throw new Error("Staging the Windows runtime is not available yet: its isolated install comes next.");
+ // Fail before output replacement or downloads; only the chosen Go directory is
+ // added to the installer's otherwise isolated PATH. No Go setup occurs here.
+ const goExecutable =
+ target === "windows-x64"
+ ? windowsBuildGo(process.env, (file) => {
+ try {
+ return lstatSync(file).isFile();
+ } catch {
+ return false;
+ }
+ })
+ : undefined;
const out = resolve(
process.env.INIT_CWD ?? process.cwd(),
options.out ?? join(REPO, "build", "runtime", target),
@@ -272,11 +276,13 @@ async function main() {
const node = await stageNode(out, target);
say("Daemon (build:runtime)");
- run("pnpm", ["--filter", "@gentle-dot/daemon", "build:runtime", "--", "--out", out], { cwd: REPO });
- const modules = installDaemonModules(out);
+ const daemonBuild = pnpmInvocation(["--filter", "@gentle-dot/daemon", "build:runtime", "--", "--out", out]);
+ run(daemonBuild.command, daemonBuild.args, { cwd: REPO });
+ const modules = installDaemonModules(out, target, goExecutable);
const engram = await stageEngram(out, target, options.engramVersion);
say("Web UI");
- run("pnpm", ["--filter", "@gentle-dot/ui", "build"], { cwd: REPO });
+ const uiBuild = pnpmInvocation(["--filter", "@gentle-dot/ui", "build"]);
+ run(uiBuild.command, uiBuild.args, { cwd: REPO });
cpSync(join(REPO, "packages", "ui", "dist", "app"), join(out, "ui"), { recursive: true });
const links = symlinksIn(out);
diff --git a/scripts/package/test/lib.test.ts b/scripts/package/test/lib.test.ts
index 9e4eb00..fc5633d 100644
--- a/scripts/package/test/lib.test.ts
+++ b/scripts/package/test/lib.test.ts
@@ -6,19 +6,24 @@ import {
assertHostTarget,
buildManifest,
checksumFor,
+ daemonSourceRevision,
engramArchiveName,
engramReleaseVersion,
+ gentleAiIntegritySummary,
hostTarget,
+ installerEnv,
nodeArchiveName,
nodeExtractionPlan,
nodeVersion,
npmWrapper,
parseArgs,
+ pnpmInvocation,
renameWhenReleased,
symlinksIn,
treeSize,
verifyChecksum,
versionFromReleaseUrl,
+ windowsBuildGo,
} from "../lib.mjs";
describe("parseArgs", () => {
@@ -200,6 +205,116 @@ describe("Windows staging downloads", () => {
});
});
+describe("Windows staging install", () => {
+ it("admits only explicitly provisioned Go and adds only its directory to installer PATH", () => {
+ const source = {
+ SystemRoot: "C:\\Windows",
+ GENTLE_DOT_BUILD_GO: "C:\\Program Files\\Go\\bin\\go.exe",
+ PATH: "C:\\private-tools",
+ SECRET: "omit",
+ };
+ expect(windowsBuildGo(source, () => true)).toBe(source.GENTLE_DOT_BUILD_GO);
+ expect(() => windowsBuildGo({}, () => true)).toThrow(/GENTLE_DOT_BUILD_GO/);
+ expect(() => windowsBuildGo(source, () => false)).toThrow(/existing/);
+ for (const value of ["go.exe", "C:\\tools;other\\go.exe", "C:\\tools\\other.exe"]) {
+ expect(() => windowsBuildGo({ GENTLE_DOT_BUILD_GO: value }, () => true)).toThrow(/GENTLE_DOT_BUILD_GO/);
+ }
+ const env = installerEnv("C:\\stage", "C:\\cache", "windows-x64", source, source.GENTLE_DOT_BUILD_GO);
+ expect(env.PATH).toBe(
+ "C:\\stage\\node\\bin;C:\\Windows\\System32;C:\\Windows;C:\\Program Files\\Go\\bin",
+ );
+ expect(env.SECRET).toBeUndefined();
+ expect(env.GENTLE_DOT_BUILD_GO).toBeUndefined();
+ expect(source.PATH).toBe("C:\\private-tools");
+ });
+
+ it("reports source-build module integrity separately from downloaded archive integrity", () => {
+ expect(
+ gentleAiIntegritySummary({
+ version: "4.0.0",
+ method: "go-sumdb-source-build",
+ package: "example/cmd/tool",
+ tag: "v4.0.0",
+ moduleChecksum: "h1:synthetic",
+ binarySha256: "abc",
+ goVersion: "go1.25.10",
+ }),
+ ).toBe(
+ "gentle-ai 4.0.0 via go-sumdb-source-build example/cmd/[email protected] (module checksum h1:synthetic; binary sha256 abc; Go go1.25.10)",
+ );
+ expect(gentleAiIntegritySummary({ version: "4.0.0", asset: "unix.tar.gz", assetSha256: "def" })).toBe(
+ "gentle-ai 4.0.0 from unix.tar.gz (sha256 def)",
+ );
+ });
+
+ it("isolates Windows installer homes, preserving only system and temporary paths", () => {
+ const source = { Path: "C:\\untrusted", SystemRoot: "C:\\Windows", TEMP: "C:\\Temp", SECRET: "omit" };
+ const before = { ...source };
+ const env = installerEnv("C:\\stage & space", "C:\\cache", "windows-x64", source);
+ expect(env.PATH).toBe("C:\\stage & space\\node\\bin;C:\\Windows\\System32;C:\\Windows");
+ expect(env).toMatchObject({
+ HOME: "C:\\cache\\npm-home",
+ USERPROFILE: "C:\\cache\\npm-home",
+ LOCALAPPDATA: "C:\\cache\\npm-home\\AppData\\Local",
+ APPDATA: "C:\\cache\\npm-home\\AppData\\Roaming",
+ SystemRoot: "C:\\Windows",
+ TEMP: "C:\\Temp",
+ TMP: "C:\\Temp",
+ });
+ expect(env.SECRET).toBeUndefined();
+ expect(source).toEqual(before);
+ expect(installerEnv("/stage", "/cache", "linux-x64", {})).toEqual({
+ HOME: "/cache/npm-home",
+ PATH: "/stage/node/bin:/usr/bin:/bin:/usr/sbin:/sbin",
+ TMPDIR: "/tmp",
+ npm_config_userconfig: "/cache/npmrc",
+ npm_config_cache: "/cache/npm-cache",
+ npm_config_registry: "https://registry.npmjs.org/",
+ npm_config_update_notifier: "false",
+ });
+ expect(installerEnv("C:\\stage", "C:\\cache", "windows-x64", { SYSTEMROOT: "C:\\Windows" }).TEMP).toBe(
+ "C:\\cache\\npm-home\\Temp",
+ );
+ expect(() => installerEnv("C:\\stage", "C:\\cache", "windows-x64", {})).toThrow(/SystemRoot/);
+ });
+
+ it("invokes pnpm through Node, not a Windows command shell or .cmd spawn", () => {
+ const args = ["--out", "C:\\space & %PATH%"];
+ expect(
+ pnpmInvocation(args, "win32", { npm_execpath: "C:\\tools & space\\pnpm.cjs" }, "C:\\Node\\node.exe"),
+ ).toEqual({ command: "C:\\Node\\node.exe", args: ["C:\\tools & space\\pnpm.cjs", ...args] });
+ expect(() => pnpmInvocation(args, "win32", { npm_execpath: "pnpm.cmd" })).toThrow(/pnpm/);
+ expect(pnpmInvocation(args, "linux", {})).toEqual({ command: "pnpm", args });
+ });
+ it("labels Windows snapshots honestly while retaining Git revision and dirty detection", () => {
+ const noGit = () => {
+ throw new Error("must not invoke git for a snapshot");
+ };
+ expect(daemonSourceRevision("C:\\snapshot", "win32", () => false, noGit)).toBe("snapshot-unversioned");
+ for (const platform of ["linux", "darwin", "win32"]) {
+ const calls: unknown[] = [];
+ const git = (command, args, options) => {
+ calls.push([command, args, options]);
+ return args[0] === "rev-parse" ? "abc123\n" : " M packages/daemon/src/cli.ts\n";
+ };
+ expect(daemonSourceRevision("/repo", platform, () => true, git)).toBe("abc123-dirty");
+ expect(calls).toEqual([
+ ["git", ["rev-parse", "HEAD"], { cwd: "/repo", encoding: "utf8" }],
+ ["git", ["status", "--porcelain", "--", "packages"], { cwd: "/repo", encoding: "utf8" }],
+ ]);
+ expect(
+ daemonSourceRevision(
+ "/repo",
+ platform,
+ () => true,
+ (_cmd, args) => (args[0] === "rev-parse" ? "abc123\n" : ""),
+ ),
+ ).toBe("abc123");
+ }
+ expect(() => daemonSourceRevision("/repo", "linux", () => false, noGit)).toThrow();
+ });
+});
+
describe("tree and manifest", () => {
it("sizes a tree without following links, and lists the links", () => {
const dir = mkdtempSync(join(tmpdir(), "stage-runtime-"));