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 a self-contained runtime and smoke-test it

Alan Buscagliaf9e5ece0c9c5
diff --git a/.gitignore b/.gitignore
index d7a6399..360eda7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,10 @@ playwright-report/
apps/desktop/src-tauri/target/
apps/desktop/src-tauri/gen/
*.log
+
+# Installer staging: downloads cache and the default runtime output
+/.cache/
+/build/
.DS_Store
# Declarations emitted next to sources by accident
diff --git a/package.json b/package.json
index 05dae3c..d529de9 100644
--- a/package.json
+++ b/package.json
@@ -9,6 +9,7 @@
"scripts": {
"dev": "pnpm --filter @gentle-dot/ui build && node packages/daemon/src/cli.ts",
"build": "pnpm --filter @gentle-dot/ui build",
+ "package:runtime": "node scripts/package/stage-runtime.mjs",
"start": "node packages/daemon/src/cli.ts",
"test": "vitest run",
"e2e": "playwright test",
diff --git a/scripts/package/lib.mjs b/scripts/package/lib.mjs
new file mode 100644
index 0000000..ac6609f
--- /dev/null
+++ b/scripts/package/lib.mjs
@@ -0,0 +1,175 @@
+// Pure helpers for staging the installed app's runtime (`stage-runtime.mjs`).
+import { createHash } from "node:crypto";
+import { createReadStream, lstatSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+/**
+ * The targets a runtime can be staged for, with the names Node's and Engram's
+ * release assets use for each.
+ */
+export const TARGETS = Object.freeze({
+ "darwin-arm64": { platform: "darwin", arch: "arm64", node: "darwin-arm64", engram: "darwin_arm64" },
+ "linux-arm64": { platform: "linux", arch: "arm64", node: "linux-arm64", engram: "linux_arm64" },
+ "linux-x64": { platform: "linux", arch: "x64", node: "linux-x64", engram: "linux_amd64" },
+});
+
+/** The Node release staged when `.nvmrc` names only a major version; it must stay on that major. */
+export const PINNED_NODE_VERSION = "24.14.1";
+
+export const USAGE =
+ "usage: stage-runtime --target <darwin-arm64|linux-arm64|linux-x64> [--out <dir>] [--engram-version <x.y.z>]";
+
+/** Parses the command line; throws with the usage on anything unexpected. */
+export function parseArgs(argv) {
+ const args = argv.filter((arg) => arg !== "--");
+ const options = {};
+ const names = { "--target": "target", "--out": "out", "--engram-version": "engramVersion" };
+ for (let i = 0; i < args.length; i += 2) {
+ const name = names[args[i]];
+ const value = args[i + 1];
+ if (!name || value === undefined || value.startsWith("--"))
+ throw new Error(`Unexpected argument ${args[i]}.\n${USAGE}`);
+ options[name] = value;
+ }
+ if (!options.target) throw new Error(`Missing --target.\n${USAGE}`);
+ if (!Object.hasOwn(TARGETS, options.target))
+ throw new Error(`Unknown target ${options.target}; expected one of ${Object.keys(TARGETS).join(", ")}.`);
+ if (options.engramVersion !== undefined && !/^\d+\.\d+\.\d+$/.test(options.engramVersion))
+ throw new Error(`--engram-version must be x.y.z, got ${options.engramVersion}.`);
+ return options;
+}
+
+/** The target this machine is, or undefined when it is none of the supported ones. */
+export function hostTarget(platform = process.platform, arch = process.arch) {
+ return Object.keys(TARGETS).find(
+ (name) => TARGETS[name].platform === platform && TARGETS[name].arch === arch,
+ );
+}
+
+/**
+ * Throws when `target` is not the machine staging it: the daemon's dependencies
+ * carry native, per-platform pieces that npm installs for the machine it runs on.
+ */
+export function assertHostTarget(target, host = hostTarget()) {
+ if (target === host) return;
+ throw new Error(
+ `Cannot stage ${target} on ${host ?? `${process.platform}-${process.arch}`}: the runtime's dependencies ` +
+ `include native pieces for the machine that installs them. Stage ${target} on a ${target} machine ` +
+ "or container (Linux targets are staged inside a container).",
+ );
+}
+
+/** The exact Node version: `.nvmrc` when it is exact, else the pinned one, which must share its major. */
+export function nodeVersion(nvmrc, pinned = PINNED_NODE_VERSION) {
+ const wanted = nvmrc.trim().replace(/^v/, "");
+ if (/^\d+\.\d+\.\d+$/.test(wanted)) return wanted;
+ if (/^\d+$/.test(wanted) && pinned.split(".")[0] === wanted) return pinned;
+ throw new Error(`.nvmrc asks for Node ${wanted}, but the pinned release is ${pinned}; update one of them.`);
+}
+
+export function nodeArchiveName(version, target) {
+ return `node-v${version}-${TARGETS[target].node}.tar.gz`;
+}
+
+export function engramArchiveName(version, target) {
+ return `engram_${version}_${TARGETS[target].engram}.tar.gz`;
+}
+
+/** 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")) {
+ const match = /^([0-9a-f]{64}) [ *](.+)$/.exec(line.trim());
+ if (match && match[2] === fileName) return match[1];
+ }
+ throw new Error(`The checksum list has no entry for ${fileName}.`);
+}
+
+export function sha256File(path) {
+ return new Promise((resolve, reject) => {
+ const hash = createHash("sha256");
+ createReadStream(path)
+ .on("data", (chunk) => hash.update(chunk))
+ .on("error", reject)
+ .on("end", () => resolve(hash.digest("hex")));
+ });
+}
+
+/** Throws when the file's SHA-256 is not `expected`. */
+export async function verifyChecksum(path, expected) {
+ const actual = await sha256File(path);
+ if (actual !== expected)
+ throw new Error(`Checksum mismatch for ${path}: expected ${expected}, got ${actual}.`);
+}
+
+/**
+ * The release version in `engram version` output, or undefined when it is not
+ * a release (a development build prints a Go pseudo-version such as `3.0.0-2026…-8e52…`).
+ */
+export function engramReleaseVersion(output) {
+ return /^engram v?(\d+\.\d+\.\d+)\s*$/.exec(output.trim())?.[1];
+}
+
+/** The `x.y.z` of a GitHub `…/releases/tag/vx.y.z` URL. */
+export function versionFromReleaseUrl(url) {
+ const version = /\/releases\/tag\/v?(\d+\.\d+\.\d+)$/.exec(url ?? "")?.[1];
+ if (!version) throw new Error(`Not a release URL: ${url}`);
+ return version;
+}
+
+/** Bytes under `dir`, counting links as themselves and never following them. */
+export function treeSize(dir) {
+ let total = 0;
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const path = join(dir, entry.name);
+ total += entry.isDirectory() ? treeSize(path) : lstatSync(path).size;
+ }
+ return total;
+}
+
+/** Symbolic links under `dir`, relative to it. */
+export function symlinksIn(dir, prefix = "") {
+ const found = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isSymbolicLink()) found.push(relative);
+ else if (entry.isDirectory()) found.push(...symlinksIn(join(dir, entry.name), relative));
+ }
+ return found;
+}
+
+export function formatSize(bytes) {
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+/** The runtime's `MANIFEST.json` content. */
+export function buildManifest({ target, versions, daemonCommit, sizeBytes, stagedAt }) {
+ for (const key of ["node", "engram", "gentlePi"])
+ if (!versions[key]) throw new Error(`The manifest needs the ${key} version.`);
+ if (!daemonCommit) throw new Error("The manifest needs the daemon commit.");
+ return {
+ name: "gentle-dot-runtime",
+ target,
+ versions,
+ daemonCommit,
+ sizeBytes,
+ size: formatSize(sizeBytes),
+ stagedAt,
+ };
+}
+
+/** A `bin/npm` or `bin/npx` that runs the staged Node's own npm, wherever the folder is copied. */
+export function npmWrapper(cli) {
+ return `#!/bin/sh
+# Runs the npm bundled with this Node; a script rather than Node's symlink, so copies that follow links work.
+self=$0
+while [ -L "$self" ]; do
+ link=$(readlink "$self")
+ case $link in
+ /*) self=$link ;;
+ *) self=$(dirname "$self")/$link ;;
+ esac
+done
+bin=$(CDPATH= cd -- "$(dirname -- "$self")" && pwd -P) || exit 1
+exec "$bin/node" "$bin/../lib/node_modules/npm/bin/${cli}" "$@"
+`;
+}
diff --git a/scripts/package/smoke-runtime.mjs b/scripts/package/smoke-runtime.mjs
new file mode 100644
index 0000000..c80e3e2
--- /dev/null
+++ b/scripts/package/smoke-runtime.mjs
@@ -0,0 +1,157 @@
+#!/usr/bin/env node
+// Starts a staged runtime's daemon the way the installed app does, on a clean HOME:
+// `node scripts/package/smoke-runtime.mjs --runtime <dir> [--read-only] [--timeout <seconds>]`.
+// It waits until the engine finished its first-run setup (`/health` idle), stops what it
+// started, and reports any file the run changed inside the runtime folder.
+import { execFileSync, spawn } from "node:child_process";
+import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync } from "node:fs";
+import { createServer } from "node:net";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+const SYSTEM_PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
+const RESERVED_PORTS = new Set([4317, 7437, 7438]);
+
+const args = process.argv.slice(2).filter((arg) => arg !== "--");
+const flag = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined);
+const say = (line) => process.stdout.write(`${line}\n`);
+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
+
+/** Path → size and modification time of every entry under `dir`, links not followed. */
+function snapshot(dir, prefix = "", into = new Map()) {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
+ const stat = lstatSync(join(dir, entry.name));
+ into.set(relative, `${stat.size}:${stat.mtimeMs}:${stat.mode}`);
+ if (entry.isDirectory()) snapshot(join(dir, entry.name), relative, into);
+ }
+ return into;
+}
+
+function changes(before, after) {
+ const changed = [];
+ for (const [path, value] of after) if (before.get(path) !== value) changed.push(path);
+ for (const path of before.keys()) if (!after.has(path)) changed.push(`${path} (removed)`);
+ return changed;
+}
+
+function freePort() {
+ return new Promise((done, fail) => {
+ const server = createServer().listen(0, "127.0.0.1", () => {
+ const { port } = server.address();
+ server.close(() => (RESERVED_PORTS.has(port) ? freePort().then(done, fail) : done(port)));
+ });
+ });
+}
+
+/** The PID listening on `port` and its command line, when `lsof` can tell. */
+function listener(port) {
+ try {
+ const pid = execFileSync("lsof", ["-t", "-n", "-P", `-iTCP:${port}`, "-sTCP:LISTEN"], {
+ encoding: "utf8",
+ env: { PATH: SYSTEM_PATH },
+ })
+ .trim()
+ .split("\n")[0];
+ const command = execFileSync("ps", ["-o", "command=", "-p", pid], { encoding: "utf8" }).trim();
+ return { pid: Number(pid), command };
+ } catch {
+ return undefined;
+ }
+}
+
+async function health(url) {
+ try {
+ const response = await fetch(new URL("/health", url), { signal: AbortSignal.timeout(2000) });
+ return await response.json();
+ } catch {
+ return undefined;
+ }
+}
+
+async function main() {
+ const source = flag("--runtime");
+ if (!source || !existsSync(join(source, "daemon", "cli.mjs")))
+ throw new Error("usage: smoke-runtime --runtime <staged runtime dir> [--read-only] [--timeout <s>]");
+ const timeoutMs = Number(flag("--timeout") ?? 240) * 1000;
+ const scratch = mkdtempSync(join(tmpdir(), "gentle-dot-smoke-"));
+ let runtime = resolve(source);
+ if (args.includes("--read-only")) {
+ runtime = join(scratch, "runtime");
+ cpSync(source, runtime, { recursive: true, verbatimSymlinks: true });
+ execFileSync("chmod", ["-R", "a-w", runtime]);
+ }
+ const home = join(scratch, "home");
+ const dataDir = join(scratch, "data");
+ mkdirSync(home);
+ const engramPort = await freePort();
+ say(`scratch ${scratch}`);
+ say(`runtime ${runtime}${args.includes("--read-only") ? " (read-only copy)" : ""}`);
+ say(`private Engram port ${engramPort}`);
+
+ const before = snapshot(runtime);
+ const logFile = join(scratch, "daemon.log");
+ const log = openSync(logFile, "a");
+ const started = Date.now();
+ // The app's bundled launch (apps/desktop daemon.rs), with nothing else from this shell.
+ const daemon = spawn(join(runtime, "node", "bin", "node"), [join(runtime, "daemon", "cli.mjs")], {
+ env: {
+ HOME: home,
+ PATH: `${join(runtime, "bin")}:${join(runtime, "node", "bin")}:${SYSTEM_PATH}`,
+ GENTLE_DOT_RUNTIME: runtime,
+ GENTLE_DOT_DATA_DIR: dataDir,
+ GENTLE_DOT_PORT: "0",
+ GENTLE_DOT_ENGRAM: "private",
+ GENTLE_DOT_ENGRAM_PORT: String(engramPort),
+ },
+ stdio: ["ignore", "pipe", log],
+ });
+ say(`daemon pid ${daemon.pid}, log ${logFile}`);
+ let url;
+ daemon.stdout.on("data", (chunk) => {
+ url ??= /running at (http:\/\/127\.0\.0\.1:\d+)/.exec(String(chunk))?.[1];
+ });
+ let exited = false;
+ daemon.on("exit", () => {
+ exited = true;
+ });
+
+ let state;
+ while (Date.now() - started < timeoutMs && !exited) {
+ if (url) state = (await health(url))?.agentState;
+ if (state === "idle" || state === "error") break;
+ await sleep(1000);
+ }
+ const seconds = ((Date.now() - started) / 1000).toFixed(1);
+ say(`daemon ${url ?? "(no URL)"}: agentState ${state ?? "unknown"} after ${seconds} s`);
+ const engram = listener(engramPort);
+ say(`engram on ${engramPort}: ${engram ? `pid ${engram.pid} ${engram.command}` : "not listening"}`);
+ const firstRun = join(dataDir, "agent", "npm", "node_modules");
+ const installed = existsSync(firstRun) ? readdirSync(firstRun) : [];
+ const companions = installed.filter((name) => /^(gentle-|pi-)/.test(name));
+ say(`first-run npm install: ${installed.length} entries (${companions.join(", ") || "no companions"})`);
+ const engineTmp = join(dataDir, "home", ".cache", "tmp");
+ say(
+ `engine TMPDIR ${engineTmp}: ${existsSync(engineTmp) ? readdirSync(engineTmp).join(", ") || "empty" : "missing"}`,
+ );
+
+ if (!exited) {
+ daemon.kill("SIGTERM");
+ for (let i = 0; i < 100 && !exited; i++) await sleep(100);
+ }
+ say(`daemon stopped: ${exited}`);
+ const left = listener(engramPort);
+ say(`engram on ${engramPort} after stop: ${left ? `still pid ${left.pid}` : "stopped"}`);
+
+ const changed = changes(before, snapshot(runtime));
+ say(`runtime files changed by the run: ${changed.length}`);
+ for (const path of changed.slice(0, 20)) say(` ${path}`);
+ const ok = state === "idle" && exited && !left && changed.length === 0;
+ say(ok ? "smoke: ok" : "smoke: FAILED");
+ process.exit(ok ? 0 : 1);
+}
+
+main().catch((error) => {
+ process.stderr.write(`smoke-runtime: ${error.message}\n`);
+ process.exit(1);
+});
diff --git a/scripts/package/stage-runtime.mjs b/scripts/package/stage-runtime.mjs
new file mode 100644
index 0000000..60c20e2
--- /dev/null
+++ b/scripts/package/stage-runtime.mjs
@@ -0,0 +1,292 @@
+#!/usr/bin/env node
+// Stages the installed app's `runtime/` folder (S29.5) for one target:
+// `node scripts/package/stage-runtime.mjs --target darwin-arm64 [--out <dir>]`.
+import { execFileSync, spawnSync } from "node:child_process";
+import {
+ chmodSync,
+ copyFileSync,
+ cpSync,
+ createWriteStream,
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { join, resolve } from "node:path";
+import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
+import { fileURLToPath } from "node:url";
+import {
+ assertHostTarget,
+ buildManifest,
+ checksumFor,
+ engramArchiveName,
+ engramReleaseVersion,
+ formatSize,
+ nodeArchiveName,
+ nodeVersion,
+ npmWrapper,
+ parseArgs,
+ symlinksIn,
+ treeSize,
+ verifyChecksum,
+ versionFromReleaseUrl,
+} 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`);
+
+function run(command, args, options = {}) {
+ const result = spawnSync(command, args, { stdio: "inherit", ...options });
+ if (result.status !== 0)
+ throw new Error(
+ `${command} ${args.join(" ")} failed (${result.error?.message ?? `exit ${result.status}`}).`,
+ );
+ return result;
+}
+
+async function download(url, destination) {
+ const response = await fetch(url);
+ if (!response.ok || !response.body) throw new Error(`GET ${url} answered ${response.status}.`);
+ const partial = `${destination}.part`;
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(partial));
+ renameSync(partial, destination);
+}
+
+async function text(url) {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`GET ${url} answered ${response.status}.`);
+ return response.text();
+}
+
+/** A cached download of `url` whose SHA-256 is `expected`, fetched again when the cached copy differs. */
+async function verifiedDownload(url, name, expected) {
+ const file = join(CACHE, name);
+ if (existsSync(file)) {
+ try {
+ await verifyChecksum(file, expected);
+ say(` cached ${name} (sha256 verified)`);
+ return file;
+ } catch {
+ unlinkSync(file);
+ }
+ }
+ say(` downloading ${url}`);
+ await download(url, file);
+ try {
+ await verifyChecksum(file, expected);
+ } catch (error) {
+ unlinkSync(file);
+ throw error;
+ }
+ say(` sha256 verified ${name}`);
+ return file;
+}
+
+/** An empty output folder; a runtime staged earlier is replaced, anything else is refused. */
+function prepareOut(out) {
+ if (existsSync(out) && readdirSync(out).length > 0) {
+ const manifest = join(out, "MANIFEST.json");
+ const previous = existsSync(manifest) && JSON.parse(readFileSync(manifest, "utf8")).name;
+ if (previous !== "gentle-dot-runtime")
+ throw new Error(`${out} is not empty and holds no staged runtime; choose an empty folder.`);
+ rmSync(out, { recursive: true });
+ }
+ mkdirSync(out, { recursive: true });
+}
+
+async function stageNode(out, target) {
+ const version = nodeVersion(readFileSync(join(REPO, ".nvmrc"), "utf8"));
+ const base = `https://nodejs.org/dist/v${version}`;
+ const archiveName = nodeArchiveName(version, target);
+ say(`Node ${version}`);
+ const archive = await verifiedDownload(
+ `${base}/${archiveName}`,
+ archiveName,
+ checksumFor(await text(`${base}/SHASUMS256.txt`), archiveName),
+ );
+ const node = join(out, "node");
+ mkdirSync(join(node, "bin"), { recursive: true });
+ const root = archiveName.replace(/\.tar\.gz$/, "");
+ // Only the binary, npm, and the license: headers, docs, and corepack are left out.
+ run("tar", [
+ "-xzf",
+ archive,
+ "-C",
+ node,
+ "--strip-components=1",
+ `${root}/bin/node`,
+ `${root}/lib/node_modules/npm`,
+ `${root}/LICENSE`,
+ ]);
+ writeFileSync(join(node, "bin", "npm"), npmWrapper("npm-cli.js"), { mode: 0o755 });
+ writeFileSync(join(node, "bin", "npx"), npmWrapper("npx-cli.js"), { mode: 0o755 });
+ return version;
+}
+
+/** The engine's packaged Gentle AI binary: readable and runnable by every user, as an installed app needs. */
+function openGentleAi(daemon) {
+ const dir = join(daemon, "node_modules", "gentle-pi", ".gentle-ai");
+ if (!existsSync(dir)) throw new Error(`gentle-pi's postinstall left no ${dir}.`);
+ const open = (path) => {
+ const stat = lstatSync(path);
+ if (stat.isDirectory()) {
+ chmodSync(path, 0o755);
+ for (const name of readdirSync(path)) open(join(path, name));
+ } else if (stat.isFile()) chmodSync(path, stat.mode & 0o111 ? 0o755 : 0o644);
+ };
+ open(dir);
+ const versions = readdirSync(dir);
+ const integrity = JSON.parse(readFileSync(join(dir, versions[0] ?? "", "integrity.json"), "utf8"));
+ return integrity;
+}
+
+function installDaemonModules(out) {
+ const daemon = join(out, "daemon");
+ const npmHome = join(CACHE, "npm-home");
+ mkdirSync(npmHome, { recursive: true });
+ const npmrc = join(CACHE, "npmrc");
+ 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 result = spawnSync(
+ join(out, "node", "bin", "node"),
+ [
+ join(out, "node", "lib", "node_modules", "npm", "bin", "npm-cli.js"),
+ "install",
+ "--omit=dev",
+ "--no-bin-links",
+ "--no-audit",
+ "--no-fund",
+ "--foreground-scripts",
+ ],
+ {
+ 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",
+ },
+ },
+ );
+ process.stdout.write(result.stdout ?? "");
+ process.stderr.write(result.stderr ?? "");
+ if (result.status !== 0) throw new Error(`npm install failed (exit ${result.status}).`);
+ const postinstall = `${result.stdout}\n${result.stderr}`
+ .split("\n")
+ .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})`);
+ const pkg = (name) =>
+ JSON.parse(readFileSync(join(daemon, "node_modules", name, "package.json"), "utf8")).version;
+ return {
+ gentlePi: pkg("gentle-pi"),
+ engine: pkg("@earendil-works/pi-coding-agent"),
+ gentleAi: gentleAi.version,
+ };
+}
+
+/** The Engram release to carry: the flag, else the user's own release version, else the latest release. */
+async function engramVersion(requested) {
+ if (requested) return { version: requested, source: "--engram-version" };
+ let installed;
+ try {
+ installed = engramReleaseVersion(
+ execFileSync("engram", ["version"], { encoding: "utf8", timeout: 5000 }),
+ );
+ } catch {}
+ if (installed) {
+ const response = await fetch(`${ENGRAM_RELEASES}/download/v${installed}/checksums.txt`, {
+ method: "HEAD",
+ });
+ if (response.ok) return { version: installed, source: "installed engram" };
+ }
+ const latest = await fetch(`${ENGRAM_RELEASES}/latest`, { redirect: "manual" });
+ return { version: versionFromReleaseUrl(latest.headers.get("location")), source: "latest release" };
+}
+
+async function stageEngram(out, target, requested) {
+ const { version, source } = await engramVersion(requested);
+ say(`Engram ${version} (${source})`);
+ const base = `${ENGRAM_RELEASES}/download/v${version}`;
+ const archiveName = engramArchiveName(version, target);
+ const archive = await verifiedDownload(
+ `${base}/${archiveName}`,
+ archiveName,
+ checksumFor(await text(`${base}/checksums.txt`), archiveName),
+ );
+ const extracted = mkdtempSync(join(CACHE, "engram-"));
+ run("tar", ["-xzf", archive, "-C", extracted, "engram"]);
+ const binary = join(extracted, "engram");
+ if (!lstatSync(binary).isFile()) throw new Error(`${archiveName} has no regular engram binary.`);
+ copyFileSync(binary, join(out, "bin", "engram"));
+ chmodSync(join(out, "bin", "engram"), 0o755);
+ rmSync(extracted, { recursive: true });
+ return { version, source };
+}
+
+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;
+}
+
+async function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const { target } = options;
+ assertHostTarget(target);
+ const out = resolve(
+ process.env.INIT_CWD ?? process.cwd(),
+ options.out ?? join(REPO, "build", "runtime", target),
+ );
+ mkdirSync(CACHE, { recursive: true });
+ prepareOut(out);
+ say(`Staging the ${target} runtime in ${out}`);
+
+ 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 engram = await stageEngram(out, target, options.engramVersion);
+ say("Web UI");
+ run("pnpm", ["--filter", "@gentle-dot/ui", "build"], { cwd: REPO });
+ cpSync(join(REPO, "packages", "ui", "dist", "app"), join(out, "ui"), { recursive: true });
+
+ const links = symlinksIn(out);
+ if (links.length > 0)
+ say(`warning: ${links.length} symbolic links remain, e.g. ${links.slice(0, 5).join(", ")}`);
+ const manifest = buildManifest({
+ target,
+ versions: { node, engram: engram.version, engramSource: engram.source, ...modules },
+ daemonCommit: daemonCommit(),
+ sizeBytes: treeSize(out),
+ stagedAt: new Date().toISOString(),
+ });
+ writeFileSync(join(out, "MANIFEST.json"), `${JSON.stringify(manifest, null, "\t")}\n`);
+ say(`Staged ${out}: ${formatSize(manifest.sizeBytes)} (${manifest.sizeBytes} bytes)`);
+}
+
+main().catch((error) => {
+ process.stderr.write(`stage-runtime: ${error.message}\n`);
+ process.exit(1);
+});
diff --git a/scripts/package/test/lib.test.ts b/scripts/package/test/lib.test.ts
new file mode 100644
index 0000000..6aa6278
--- /dev/null
+++ b/scripts/package/test/lib.test.ts
@@ -0,0 +1,125 @@
+import { mkdtempSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ assertHostTarget,
+ buildManifest,
+ checksumFor,
+ engramArchiveName,
+ engramReleaseVersion,
+ hostTarget,
+ nodeArchiveName,
+ nodeVersion,
+ parseArgs,
+ symlinksIn,
+ treeSize,
+ verifyChecksum,
+ versionFromReleaseUrl,
+} from "../lib.mjs";
+
+describe("parseArgs", () => {
+ it("reads the target, the output folder, and an Engram version, ignoring pnpm's --", () => {
+ expect(
+ parseArgs(["--", "--target", "linux-x64", "--out", "/tmp/r", "--engram-version", "3.2.1"]),
+ ).toEqual({ target: "linux-x64", out: "/tmp/r", engramVersion: "3.2.1" });
+ });
+
+ it("refuses a missing or unknown target, unknown flags, and a flag without a value", () => {
+ expect(() => parseArgs(["--out", "/tmp/r"])).toThrow(/Missing --target/);
+ expect(() => parseArgs(["--target", "windows-x64"])).toThrow(/Unknown target windows-x64/);
+ expect(() => parseArgs(["--target", "linux-x64", "--force", "1"])).toThrow(/Unexpected argument --force/);
+ expect(() => parseArgs(["--target", "--out", "/tmp/r"])).toThrow(/Unexpected argument --target/);
+ expect(() => parseArgs(["--target", "linux-x64", "--engram-version", "latest"])).toThrow(/x\.y\.z/);
+ });
+});
+
+describe("host target", () => {
+ it("maps Node's platform and arch to a target", () => {
+ expect(hostTarget("darwin", "arm64")).toBe("darwin-arm64");
+ expect(hostTarget("linux", "x64")).toBe("linux-x64");
+ expect(hostTarget("darwin", "x64")).toBeUndefined();
+ });
+
+ it("refuses to stage another platform's runtime, naming the way out", () => {
+ expect(() => assertHostTarget("darwin-arm64", "darwin-arm64")).not.toThrow();
+ expect(() => assertHostTarget("linux-arm64", "darwin-arm64")).toThrow(
+ /Cannot stage linux-arm64 on darwin-arm64.*inside a container/,
+ );
+ });
+});
+
+describe("versions and asset names", () => {
+ it("uses an exact .nvmrc, else the pinned release of the same major", () => {
+ expect(nodeVersion("24.9.0\n")).toBe("24.9.0");
+ expect(nodeVersion("v24", "24.14.1")).toBe("24.14.1");
+ expect(() => nodeVersion("22", "24.14.1")).toThrow(/Node 22/);
+ });
+
+ it("names the official archives", () => {
+ expect(nodeArchiveName("24.14.1", "linux-x64")).toBe("node-v24.14.1-linux-x64.tar.gz");
+ expect(engramArchiveName("3.2.1", "linux-x64")).toBe("engram_3.2.1_linux_amd64.tar.gz");
+ expect(engramArchiveName("3.2.1", "darwin-arm64")).toBe("engram_3.2.1_darwin_arm64.tar.gz");
+ });
+
+ it("takes a release version from `engram version`, not a development build", () => {
+ expect(engramReleaseVersion("engram 3.2.1\n")).toBe("3.2.1");
+ expect(engramReleaseVersion("engram v3.1.0")).toBe("3.1.0");
+ expect(engramReleaseVersion("engram 3.0.0-20261007205017-8e525e767d69")).toBeUndefined();
+ expect(engramReleaseVersion("")).toBeUndefined();
+ });
+
+ it("reads the version of a release URL", () => {
+ expect(versionFromReleaseUrl("https://github.com/o/engram/releases/tag/v3.2.1")).toBe("3.2.1");
+ expect(() => versionFromReleaseUrl("https://github.com/o/engram/releases")).toThrow(/Not a release URL/);
+ });
+});
+
+describe("checksums", () => {
+ const hello = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
+ const listing = `${"a".repeat(64)} node-v24.14.1-linux-x64.tar.gz\n${hello} hello.txt\n${"b".repeat(64)} *bin.zip\n`;
+
+ it("finds a file's entry in SHASUMS256 / checksums.txt listings", () => {
+ expect(checksumFor(listing, "hello.txt")).toBe(hello);
+ expect(checksumFor(listing, "bin.zip")).toBe("b".repeat(64));
+ expect(() => checksumFor(listing, "node-v24.14.1-linux-x64.tar")).toThrow(/no entry/);
+ });
+
+ it("accepts a matching file and rejects a tampered one", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "stage-runtime-"));
+ const file = join(dir, "hello.txt");
+ writeFileSync(file, "hello");
+ await expect(verifyChecksum(file, hello)).resolves.toBeUndefined();
+ writeFileSync(file, "hellO");
+ await expect(verifyChecksum(file, hello)).rejects.toThrow(/Checksum mismatch/);
+ });
+});
+
+describe("tree and manifest", () => {
+ it("sizes a tree without following links, and lists the links", () => {
+ const dir = mkdtempSync(join(tmpdir(), "stage-runtime-"));
+ writeFileSync(join(dir, "a"), "12345");
+ symlinkSync("a", join(dir, "link"));
+ expect(treeSize(dir)).toBe(5 + 1);
+ expect(symlinksIn(dir)).toEqual(["link"]);
+ });
+
+ it("records the versions, the commit, and the size", () => {
+ const manifest = buildManifest({
+ target: "darwin-arm64",
+ versions: { node: "24.14.1", engram: "3.2.1", gentlePi: "4.0.0" },
+ daemonCommit: "abc123",
+ sizeBytes: 3 * 1024 * 1024,
+ stagedAt: "2026-10-09T00:00:00.000Z",
+ });
+ expect(manifest).toMatchObject({ name: "gentle-dot-runtime", size: "3.0 MB", daemonCommit: "abc123" });
+ expect(() =>
+ buildManifest({
+ target: "darwin-arm64",
+ versions: { node: "24.14.1" },
+ daemonCommit: "x",
+ sizeBytes: 0,
+ }),
+ ).toThrow(/engram/);
+ });
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index 6c7a7f1..c3ee0e2 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -6,7 +6,11 @@ export default defineConfig({
{
test: {
name: "node",
- include: ["packages/protocol/test/**/*.test.ts", "packages/daemon/test/**/*.test.ts"],
+ include: [
+ "packages/protocol/test/**/*.test.ts",
+ "packages/daemon/test/**/*.test.ts",
+ "scripts/package/test/**/*.test.ts",
+ ],
environment: "node",
testTimeout: 20_000,
},