Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
fix(npx-cli): verify Bun/uv runtime downloads against vendor SHA-256 (#6711) (#6752)
Leon.Cb53b132d57f3
diff --git a/src/npx-cli/install/setup-runtime.ts b/src/npx-cli/install/setup-runtime.tsindex ff7d2671b..69b8266be 100644--- a/src/npx-cli/install/setup-runtime.ts+++ b/src/npx-cli/install/setup-runtime.ts@@ -1,7 +1,9 @@-import { existsSync, readFileSync, writeFileSync } from 'fs';-import { execFile, execSync } from 'child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';+import { execFile, spawnSync } from 'child_process';+import { createHash } from 'crypto';import { createRequire } from 'module';-import { join } from 'path';+import { dirname, join } from 'path';+import { gunzipSync, inflateRawSync } from 'zlib';import { classifyError, ErrorSeverity } from './error-taxonomy.js';import { installerError, type InstallSummary } from './error-reporter.js';import { USER_SETTINGS_PATH } from '../../shared/paths.js';@@ -143,21 +145,277 @@ function describeExecError(error: unknown, includeStdoutWithStderr = false): strreturn String(error);}-/** Run the platform-specific Bun installer, then confirm the binary is resolvable. */-function runBunInstaller(): void {- if (IS_WINDOWS) {- execSync('powershell -c "irm https://bun.sh/install.ps1 | iex"', {- stdio: 'pipe',- timeout: INSTALL_TIMEOUT_MS,- shell: process.env.ComSpec ?? 'cmd.exe',+type RuntimeTool = 'bun' | 'uv';+type RuntimeLibc = 'glibc' | 'musl';++/** Probe only when selecting an install asset; unavailable ldd keeps the glibc default. */+export function detectRuntimeLibc(platform: NodeJS.Platform = process.platform): RuntimeLibc {+ if (platform === 'linux') {+ try {+ const { stdout, stderr } = spawnSync('ldd', ['--version'], {+ encoding: 'utf8',+ shell: false,+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 1_000,+ });+ // musl can report its version on stderr with a nonzero exit status.+ if (/musl/i.test(`${stdout ?? ''}\n${stderr ?? ''}`)) return 'musl';+ } catch {+ // A missing or unreadable ldd must never prevent installation.+ }+ }+ return 'glibc';+}++/** Fetches vendor release assets; tests replace it so they never use the network. */+export type RuntimeReleaseAssetDownload = (url: string, timeoutMs: number) => Promise<Buffer>;++/**+ * Runs `<staged binary> --version` before it is installed; tests replace it,+ * since their fixture binaries are not real executables.+ */+export type RuntimeExecutableProbe = (executablePath: string) => boolean | Promise<boolean>;++export interface RuntimeInstallProbes {+ probeExecutable?: RuntimeExecutableProbe;+ /** Whether this x64 process runs under Rosetta 2 on Apple silicon. */+ isRosettaTranslated?: () => boolean;+}++/** Same probe and one-second retry ensureBun applies to an installed binary. */+async function stagedExecutableRuns(executablePath: string): Promise<boolean> {+ const runs = (): boolean => {+ try {+ return spawnVersionProbe(executablePath, ['--version']).status === 0;+ } catch {+ return false;+ }+ };+ if (runs()) return true;+ await new Promise((r) => setTimeout(r, 1000));+ return runs();+}++/** Bun's install.sh check: an x64 shell on Apple silicon still gets the native build. */+export function isRosettaTranslated(): boolean {+ try {+ const { stdout } = spawnSync('sysctl', ['-n', 'sysctl.proc_translated'], {+ encoding: 'utf8',+ shell: false,+ stdio: ['ignore', 'pipe', 'ignore'],+ // The same budget as the ldd probe: sysctl answers from the kernel.+ timeout: 1_000,});+ return (stdout ?? '').trim() === '1';+ } catch {+ // Without sysctl, keep the architecture the process reports.+ return false;+ }+}++/** `baseline` selects Bun's build for x64 CPUs without AVX2. */+export function runtimeReleaseAsset(+ tool: RuntimeTool,+ platform: NodeJS.Platform = process.platform,+ arch: string = process.arch,+ libc: RuntimeLibc = detectRuntimeLibc(platform),+ baseline = false,+): string {+ if (!['linux', 'darwin', 'win32'].includes(platform) || !['x64', 'arm64'].includes(arch)) {+ throw new Error(`No ${tool} release asset is known for ${platform}-${arch}`);+ }+ if (baseline && (tool !== 'bun' || arch !== 'x64')) {+ throw new Error(`No baseline ${tool} release asset exists for ${platform}-${arch}`);+ }+ if (tool === 'bun') {+ const suffix = (platform === 'linux' && libc === 'musl' ? '-musl' : '') + (baseline ? '-baseline' : '');+ return `bun-${platform === 'win32' ? 'windows' : platform}-${arch === 'arm64' ? 'aarch64' : 'x64'}${suffix}.zip`;+ }+ const target = platform === 'win32' ? 'pc-windows-msvc' : platform === 'darwin' ? 'apple-darwin' : `unknown-linux-${libc === 'musl' ? 'musl' : 'gnu'}`;+ return `uv-${arch === 'arm64' ? 'aarch64' : 'x86_64'}-${target}.${platform === 'win32' ? 'zip' : 'tar.gz'}`;+}++/** Both vendors publish sha256sum lines. Only the exact asset name can authorize it. */+export function parseRuntimeChecksum(checksums: string, assetName: string): string {+ const matches = checksums.split(/\r?\n/).flatMap(line => {+ const match = /^([0-9a-f]{64})[ \t]+\*?([^\r\n]+)$/i.exec(line);+ return match && match[2] === assetName ? [match[1].toLowerCase()] : [];+ });+ if (matches.length !== 1) throw new Error(`Expected one SHA-256 entry for ${assetName}, found ${matches.length}`);+ return matches[0];+}++async function downloadRuntimeAsset(url: string, timeoutMs: number): Promise<Buffer> {+ const signal = timeoutMs === 0 ? undefined : AbortSignal.timeout(timeoutMs);+ const response = await fetch(url, { signal, redirect: 'follow' });+ if (!response.ok) throw new Error(`GET ${url} answered HTTP ${response.status}`);+ return Buffer.from(await response.arrayBuffer());+}++/** Read selected regular files only; archive paths are never used as disk paths. */+function runtimeExecutables(archive: Buffer, assetName: string, binaries: string[]): Map<string, Buffer> {+ const extracted = new Map<string, Buffer>();+ const stem = assetName.replace(/\.(zip|tar\.gz)$/, '');+ const select = (name: string): string | undefined => binaries.find(binary => name === binary || name === `${stem}/${binary}`);+ const add = (binary: string, bytes: Buffer): void => {+ if (extracted.has(binary)) throw new Error(`Duplicate ${binary} in ${assetName}`);+ if (!bytes.length) throw new Error(`Empty ${binary} in ${assetName}`);+ extracted.set(binary, bytes);+ };+ if (assetName.endsWith('.zip')) {+ // Follow tree-sitter-cli-conda's central-directory reader, also accepting+ // deflated entries. No external extraction tool or runtime package is needed.+ let eocd = -1;+ for (let offset = archive.length - 22; offset >= Math.max(0, archive.length - 22 - 0xffff); offset--) {+ if (archive.readUInt32LE(offset) === 0x06054b50 && offset + 22 + archive.readUInt16LE(offset + 20) === archive.length) {+ eocd = offset;+ break;+ }+ }+ if (eocd < 0) throw new Error(`No ZIP central directory in ${assetName}`);+ const entries = archive.readUInt16LE(eocd + 10);+ const centralStart = archive.readUInt32LE(eocd + 16);+ const centralEnd = centralStart + archive.readUInt32LE(eocd + 12);+ if (archive.readUInt32LE(eocd + 4) !== 0 || archive.readUInt16LE(eocd + 8) !== entries || centralEnd > eocd) {+ throw new Error(`Unsupported ZIP central directory in ${assetName}`);+ }+ let offset = centralStart;+ for (let entry = 0; entry < entries; entry++) {+ if (offset + 46 > centralEnd || archive.readUInt32LE(offset) !== 0x02014b50) {+ throw new Error(`Corrupt ZIP central directory in ${assetName}`);+ }+ const method = archive.readUInt16LE(offset + 10);+ const compressedSize = archive.readUInt32LE(offset + 20);+ const size = archive.readUInt32LE(offset + 24);+ const nameLength = archive.readUInt16LE(offset + 28);+ const next = offset + 46 + nameLength + archive.readUInt16LE(offset + 30) + archive.readUInt16LE(offset + 32);+ if (next > centralEnd) throw new Error(`Truncated ZIP entry in ${assetName}`);+ const name = archive.toString('utf8', offset + 46, offset + 46 + nameLength);+ const binary = select(name);+ if (binary) {+ const fileType = (archive.readUInt32LE(offset + 38) >>> 16) & 0o170000;+ if (fileType !== 0 && fileType !== 0o100000) throw new Error(`${name} is not a regular file`);+ if ((archive.readUInt16LE(offset + 8) & 1) || ![0, 8].includes(method)) {+ throw new Error(`Unsupported ZIP compression for ${name}`);+ }+ const local = archive.readUInt32LE(offset + 42);+ if (local + 30 > centralStart || archive.readUInt32LE(local) !== 0x04034b50) {+ throw new Error(`Corrupt ZIP local header for ${name}`);+ }+ const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);+ if (start + compressedSize > centralStart) throw new Error(`Truncated ZIP data for ${name}`);+ const compressed = archive.subarray(start, start + compressedSize);+ const bytes = method === 0 ? compressed : inflateRawSync(compressed);+ if (bytes.length !== size) throw new Error(`Incorrect ZIP entry size for ${name}`);+ add(binary, bytes);+ }+ offset = next;+ }} else {- execSync('curl -fsSL https://bun.sh/install | bash', {- stdio: 'pipe',- timeout: INSTALL_TIMEOUT_MS,- shell: '/bin/bash',- });+ // Like tree-sitter-cli-conda's tar reader, but for uv's gzip archive.+ const tar = gunzipSync(archive);+ const field = (header: Buffer, start: number, length: number): string =>+ header.subarray(start, start + length).toString('utf8').split('\0')[0];+ for (let offset = 0; offset < tar.length;) {+ if (offset + 512 > tar.length) throw new Error(`Truncated tar header in ${assetName}`);+ const header = tar.subarray(offset, offset + 512);+ if (header.every(byte => byte === 0)) break;+ const prefix = field(header, 345, 155);+ const name = (prefix ? `${prefix}/` : '') + field(header, 0, 100);+ const sizeField = field(header, 124, 12).trim();+ if (!/^[0-7]+$/.test(sizeField)) throw new Error(`Invalid tar entry size in ${assetName}`);+ const size = parseInt(sizeField, 8);+ const start = offset + 512;+ const end = start + Math.ceil(size / 512) * 512;+ if (!Number.isSafeInteger(end) || end > tar.length) throw new Error(`Truncated tar entry in ${assetName}`);+ const binary = select(name.replace(/^\.\//, ''));+ if (binary) {+ if (header[156] !== 0 && header[156] !== 0x30) throw new Error(`${name} is not a regular file`);+ add(binary, tar.subarray(start, start + size));+ }+ offset = end;+ }}+ if (!extracted.has(binaries[0])) throw new Error(`No ${binaries[0]} executable in ${assetName}`);+ return extracted;+}++/**+ * Verify before opening the archive; stage complete binaries beside their+ * destination and install them only after the staged primary runs.+ */+export async function installRuntimeRelease(+ tool: RuntimeTool,+ executablePath: string,+ downloadReleaseAsset: RuntimeReleaseAssetDownload = downloadRuntimeAsset,+ platform: NodeJS.Platform = process.platform,+ arch: string = process.arch,+ libc: RuntimeLibc = detectRuntimeLibc(platform),+ probes: RuntimeInstallProbes = {},+): Promise<void> {+ const probeExecutable = probes.probeExecutable ?? stagedExecutableRuns;+ const translated = platform === 'darwin' && arch === 'x64' && (probes.isRosettaTranslated ?? isRosettaTranslated)();+ const assetArch = translated ? 'arm64' : arch;+ const assetName = runtimeReleaseAsset(tool, platform, assetArch, libc);+ // Bun's installers pick the baseline build on x64 CPUs without AVX2 (old+ // CPUs, many VMs). Rather than read CPU flags, try the baseline when the+ // regular build doesn't run here.+ const assetNames = tool === 'bun' && assetArch === 'x64'+ ? [assetName, runtimeReleaseAsset(tool, platform, assetArch, libc, true)]+ : [assetName];+ const baseUrl = `https://github.com/${tool === 'bun' ? 'oven-sh/bun' : 'astral-sh/uv'}/releases/latest/download`;+ const deadline = INSTALL_TIMEOUT_MS === 0 ? undefined : Date.now() + INSTALL_TIMEOUT_MS;+ const download = (name: string): Promise<Buffer> => {+ const remainingMs = deadline === undefined ? 0 : deadline - Date.now();+ if (deadline !== undefined && remainingMs <= 0) throw new Error(`${tool} release download timed out`);+ return downloadReleaseAsset(`${baseUrl}/${name}`, remainingMs);+ };+ const checksums = (await download(tool === 'bun' ? 'SHASUMS256.txt' : `${assetName}.sha256`)).toString('utf8');+ const suffix = platform === 'win32' ? '.exe' : '';+ const binaries = tool === 'bun' ? [`bun${suffix}`] : [`uv${suffix}`, `uvx${suffix}`];+ const notRunnable: string[] = [];+ for (const name of assetNames) {+ const expected = parseRuntimeChecksum(checksums, name);+ // Downloads stay in memory, so a failed request or verification leaves no partial file.+ const archive = await download(name);+ const actual = createHash('sha256').update(archive).digest('hex');+ if (actual !== expected) {+ throw new Error(`${name} has SHA-256 ${actual}, not the vendor's ${expected}; it was not opened`);+ }+ const extracted = runtimeExecutables(archive, name, binaries);+ const binDir = dirname(executablePath);+ mkdirSync(binDir, { recursive: true });+ const stagingDir = mkdtempSync(join(binDir, '.runtime-'));+ try {+ for (const [binary, bytes] of extracted) {+ const staged = join(stagingDir, binary);+ writeFileSync(staged, bytes);+ if (platform !== 'win32') chmodSync(staged, 0o755);+ }+ // A build this CPU can't run must never replace a working binary.+ if (!(await probeExecutable(join(stagingDir, binaries[0])))) {+ notRunnable.push(name);+ continue;+ }+ // Install the primary executable last, after its optional companion.+ for (const binary of [...binaries].reverse()) {+ if (extracted.has(binary)) {+ renameSync(join(stagingDir, binary), binary === binaries[0] ? executablePath : join(binDir, binary));+ }+ }+ return;+ } finally {+ rmSync(stagingDir, { recursive: true, force: true });+ }+ }+ throw new Error(+ `${notRunnable.join(' and ')} verified but \`${binaries[0]} --version\` did not run on this machine; nothing was installed`,+ );+}++/** Install verified Bun binaries, then confirm the binary is resolvable. */+async function runBunInstaller(): Promise<void> {+ await installRuntimeRelease('bun', bunCommonPaths()[0]);if (!isBunInstalled()) {throw new Error(@@ -166,9 +424,9 @@ function runBunInstaller(): void {}}-function installBun(): void {+async function installBun(): Promise<void> {try {- runBunInstaller();+ await runBunInstaller();} catch (error) {const err = error instanceof Error ? error : new Error(String(error));const manualInstructions = IS_WINDOWS@@ -181,21 +439,9 @@ function installBun(): void {}}-/** Run the platform-specific uv installer, then confirm the binary is resolvable. */-function runUvInstaller(): void {- if (IS_WINDOWS) {- execSync('powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"', {- stdio: 'pipe',- timeout: INSTALL_TIMEOUT_MS,- shell: process.env.ComSpec ?? 'cmd.exe',- });- } else {- execSync('curl -LsSf https://astral.sh/uv/install.sh | sh', {- stdio: 'pipe',- timeout: INSTALL_TIMEOUT_MS,- shell: '/bin/bash',- });- }+/** Install verified uv binaries, then confirm the binary is resolvable. */+async function runUvInstaller(): Promise<void> {+ await installRuntimeRelease('uv', uvCommonPaths()[0]);if (!isUvInstalled()) {throw new Error(@@ -204,9 +450,9 @@ function runUvInstaller(): void {}}-function installUv(): void {+async function installUv(): Promise<void> {try {- runUvInstaller();+ await runUvInstaller();} catch (error) {const err = error instanceof Error ? error : new Error(String(error));const manualInstructions = IS_WINDOWS@@ -309,7 +555,7 @@ export async function ensureBun(summary?: InstallSummary): Promise<{ bunPath: st// the central decision point so it becomes a loud ABORT (bun is mandatory// for hooks — there is no opt-out).try {- installBun();+ await installBun();} catch (error: unknown) {const err = error instanceof Error ? error : new Error(String(error));// installerError(ABORT) reports the cause loudly and always throws.@@ -370,7 +616,7 @@ export async function ensureUv(const sum = summaryOrEphemeral(summary);if (!isUvInstalled()) {try {- installUv();+ await installUv();} catch (error: unknown) {const err = error instanceof Error ? error : new Error(String(error));if (options.allowVectorSearchOptOut && userHasOptedOutOfVectorSearch()) {diff --git a/tests/setup-runtime.test.ts b/tests/setup-runtime.test.tsindex 90cbefcb0..a006179d2 100644--- a/tests/setup-runtime.test.ts+++ b/tests/setup-runtime.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test';-import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, chmodSync, readdirSync, copyFileSync, symlinkSync } from 'fs';+import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, chmodSync, readdirSync, copyFileSync, symlinkSync, statSync } from 'fs';import { spawnSync } from 'child_process';import * as childProcess from 'node:child_process';import { createHash } from 'crypto';@@ -15,7 +15,13 @@ import {installPluginDependencies,ensureServerEmbedder,provisionTreeSitterCli,+ detectRuntimeLibc,+ runtimeReleaseAsset,+ parseRuntimeChecksum,+ installRuntimeRelease,+ type RuntimeReleaseAssetDownload,} from '../src/npx-cli/install/setup-runtime';+import { tarOf, zipOf } from './helpers/fake-conda-package';import { ensureTreeSitterCliBinary, isTreeSitterCliBinaryUsable, treeSitterCliBinaryPath } from '../src/services/smart-file-read/tree-sitter-cli-provision';import { pinnedTreeSitterExecutableSha256, treeSitterReleaseAssetUrl } from '../src/services/smart-file-read/tree-sitter-cli-checksums';import { createInstallSummary, InstallAbortError } from '../src/npx-cli/install/error-reporter';@@ -173,6 +179,499 @@ describe('setup-runtime binary detection honours installer env vars', () => {});});+describe('runtime libc detection', () => {+ function stubLdd() {+ return spyOn(childProcess, 'spawnSync').mockReturnValue({+ pid: 0, output: [], stdout: '', stderr: '', status: 0, signal: null,+ });+ }+ let ldd: ReturnType<typeof stubLdd>;++ beforeEach(() => { ldd = stubLdd(); });+ afterEach(() => { ldd.mockRestore(); });++ it.each([+ ['musl on stdout', 'musl libc (x86_64)\nVersion 1.2.5', '', 0, 'musl'],+ ['musl on stderr', '', 'musl libc (aarch64)\nVersion 1.2.5', 1, 'musl'],+ ['glibc', 'ldd (GNU libc) 2.40', '', 0, 'glibc'],+ ['empty output', '', '', 0, 'glibc'],+ ['missing ldd', null, null, null, 'glibc'],+ ] as const)('detects libc with %s', (_name, stdout, stderr, status, expected) => {+ ldd.mockReturnValue({+ pid: 0, output: [], stdout, stderr, status, signal: null,+ ...(status === null ? { error: Object.assign(new Error('spawnSync ldd ENOENT'), { code: 'ENOENT' }) } : {}),+ } as ReturnType<typeof spawnSync>);++ expect(detectRuntimeLibc('linux')).toBe(expected);+ expect(ldd).toHaveBeenCalledWith('ldd', ['--version'], {+ encoding: 'utf8', shell: false, stdio: ['ignore', 'pipe', 'pipe'], timeout: 1_000,+ });+ for (const tool of ['bun', 'uv'] as const) {+ for (const arch of ['x64', 'arm64']) {+ expect(runtimeReleaseAsset(tool, 'linux', arch)).toBe(runtimeReleaseAsset(tool, 'linux', arch, expected));+ }+ }+ });++ it('falls back to glibc when the probe throws', () => {+ ldd.mockImplementation(() => { throw new Error('ldd output could not be read'); });+ expect(detectRuntimeLibc('linux')).toBe('glibc');+ expect(runtimeReleaseAsset('bun', 'linux', 'x64')).toBe('bun-linux-x64.zip');+ expect(runtimeReleaseAsset('uv', 'linux', 'x64')).toBe('uv-x86_64-unknown-linux-gnu.tar.gz');+ });++ it.each(['darwin', 'win32'] as const)('does not probe ldd on %s', platform => {+ expect(detectRuntimeLibc(platform)).toBe('glibc');+ runtimeReleaseAsset('bun', platform, 'x64');+ runtimeReleaseAsset('uv', platform, 'arm64');+ expect(ldd).not.toHaveBeenCalled();+ });++ it('does not probe ldd when libc is overridden', () => {+ expect(runtimeReleaseAsset('bun', 'linux', 'x64', 'musl')).toBe('bun-linux-x64-musl.zip');+ expect(runtimeReleaseAsset('uv', 'linux', 'arm64', 'glibc')).toBe('uv-aarch64-unknown-linux-gnu.tar.gz');+ expect(ldd).not.toHaveBeenCalled();+ });+});++describe('verified runtime release installation', () => {+ let root: string;+ const executable = Buffer.from('#!/bin/sh\nexit 77\n');+ // Fixture binaries are not real executables; the probe tests below exercise a failing probe.+ const runs = { probeExecutable: () => true, isRosettaTranslated: () => false };+ const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex');+ const platforms = [+ ['linux', 'x64', 'glibc', 'bun-linux-x64.zip', 'uv-x86_64-unknown-linux-gnu.tar.gz'],+ ['linux', 'arm64', 'glibc', 'bun-linux-aarch64.zip', 'uv-aarch64-unknown-linux-gnu.tar.gz'],+ ['darwin', 'x64', 'glibc', 'bun-darwin-x64.zip', 'uv-x86_64-apple-darwin.tar.gz'],+ ['darwin', 'arm64', 'glibc', 'bun-darwin-aarch64.zip', 'uv-aarch64-apple-darwin.tar.gz'],+ ['win32', 'x64', 'glibc', 'bun-windows-x64.zip', 'uv-x86_64-pc-windows-msvc.zip'],+ ['win32', 'arm64', 'glibc', 'bun-windows-aarch64.zip', 'uv-aarch64-pc-windows-msvc.zip'],+ ['linux', 'x64', 'musl', 'bun-linux-x64-musl.zip', 'uv-x86_64-unknown-linux-musl.tar.gz'],+ ['linux', 'arm64', 'musl', 'bun-linux-aarch64-musl.zip', 'uv-aarch64-unknown-linux-musl.tar.gz'],+ ['darwin', 'x64', 'musl', 'bun-darwin-x64.zip', 'uv-x86_64-apple-darwin.tar.gz'],+ ['darwin', 'arm64', 'musl', 'bun-darwin-aarch64.zip', 'uv-aarch64-apple-darwin.tar.gz'],+ ['win32', 'x64', 'musl', 'bun-windows-x64.zip', 'uv-x86_64-pc-windows-msvc.zip'],+ ['win32', 'arm64', 'musl', 'bun-windows-aarch64.zip', 'uv-aarch64-pc-windows-msvc.zip'],+ ] as const;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'verified-runtime-'));+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ function archiveFor(asset: string, includeUvx = true): Buffer {+ const stem = asset.replace(/\.(zip|tar\.gz)$/, '');+ const isWindows = asset.includes('windows');+ const primary = `${asset.startsWith('bun-') ? 'bun' : 'uv'}${isWindows ? '.exe' : ''}`;+ // Bun uses a wrapper directory; uv's Windows ZIP has root-level binaries.+ const prefix = isWindows && asset.startsWith('uv-') ? '' : `${stem}/`;+ const files: Record<string, Buffer> = { [`${prefix}${primary}`]: executable };+ if (asset.startsWith('uv-') && includeUvx) files[`${prefix}uvx${isWindows ? '.exe' : ''}`] = executable;+ return asset.endsWith('.zip') ? zipOf(files, Object.keys(files)) : gzipSync(tarOf(files));+ }++ function serving(asset: string, archive = archiveFor(asset), checksums = `${sha256(archive)} ${asset}\n`) {+ const downloads: string[] = [];+ const download: RuntimeReleaseAssetDownload = async (url, timeoutMs) => {+ downloads.push(url);+ expect(timeoutMs).toBeGreaterThan(0);+ const base = `https://github.com/${asset.startsWith('bun-') ? 'oven-sh/bun' : 'astral-sh/uv'}/releases/latest/download/`;+ if (url === `${base}${asset}`) return archive;+ if (url === `${base}${asset.startsWith('bun-') ? 'SHASUMS256.txt' : `${asset}.sha256`}`) return Buffer.from(checksums);+ throw new Error(`Unexpected download: ${url}`);+ };+ return { download, downloads };+ }++ it.each(platforms)('selects and installs verified assets for %s-%s (%s)', async (platform, arch, libc, bunAsset, uvAsset) => {+ for (const [tool, asset] of [['bun', bunAsset], ['uv', uvAsset]] as const) {+ expect(runtimeReleaseAsset(tool, platform, arch, libc)).toBe(asset);+ const binary = `${tool}${platform === 'win32' ? '.exe' : ''}`;+ const destination = join(root, tool, binary);+ const { download, downloads } = serving(asset);++ await installRuntimeRelease(tool, destination, download, platform, arch, libc, runs);++ expect(readFileSync(destination)).toEqual(executable);+ if (tool === 'uv') expect(readFileSync(join(dirname(destination), `uvx${platform === 'win32' ? '.exe' : ''}`))).toEqual(executable);+ if (platform !== 'win32' && !IS_WINDOWS) expect(statSync(destination).mode & 0o777).toBe(0o755);+ expect(downloads).toHaveLength(2);+ expect(readdirSync(dirname(destination)).some(name => name.startsWith('.runtime-'))).toBe(false);+ }+ });++ it.each([+ ['musl', '', 'musl libc (x86_64)', 1, 'bun-linux-x64-musl.zip', 'uv-x86_64-unknown-linux-musl.tar.gz'],+ ['glibc', 'ldd (GNU libc) 2.40', '', 0, 'bun-linux-x64.zip', 'uv-x86_64-unknown-linux-gnu.tar.gz'],+ ['missing ldd', null, null, null, 'bun-linux-x64.zip', 'uv-x86_64-unknown-linux-gnu.tar.gz'],+ ] as const)('installs the detected default assets with %s', async (_name, stdout, stderr, status, bunAsset, uvAsset) => {+ const ldd = spyOn(childProcess, 'spawnSync').mockReturnValue({+ pid: 0, output: [], stdout, stderr, status, signal: null,+ ...(status === null ? { error: Object.assign(new Error('spawnSync ldd ENOENT'), { code: 'ENOENT' }) } : {}),+ } as ReturnType<typeof spawnSync>);+ try {+ for (const [tool, asset] of [['bun', bunAsset], ['uv', uvAsset]] as const) {+ const destination = join(root, tool, tool);+ const { download, downloads } = serving(asset);+ await installRuntimeRelease(tool, destination, download, 'linux', 'x64', undefined, runs);+ expect(readFileSync(destination)).toEqual(executable);+ expect(downloads).toHaveLength(2);+ }+ expect(ldd).toHaveBeenCalledTimes(2);+ } finally {+ ldd.mockRestore();+ }+ });++ it('writes to the env-directed paths used by the unchanged probes', async () => {+ const destinations = [+ ['bun', bunCommonPaths({ BUN_INSTALL: join(root, 'bun') })[0]],+ ['uv', uvCommonPaths({ UV_INSTALL_DIR: join(root, 'uv') })[0]],+ ] as const;+ for (const [tool, destination] of destinations) {+ const asset = runtimeReleaseAsset(tool, process.platform, process.arch, 'glibc');+ await installRuntimeRelease(tool, destination, serving(asset).download, process.platform, process.arch, 'glibc', runs);+ expect(readFileSync(destination)).toEqual(executable);+ }+ });++ it.each(['bun', 'uv'] as const)('%s rejects unsupported platforms and architectures before downloading', async tool => {+ for (const [platform, arch] of [['freebsd', 'x64'], ['linux', 'ia32'], ['linux', 'riscv64']] as const) {+ const { download, downloads } = serving(runtimeReleaseAsset(tool, 'linux', 'x64', 'glibc'));+ await expect(installRuntimeRelease(tool, join(root, tool), download, platform, arch, 'glibc', runs))+ .rejects.toThrow(`No ${tool} release asset is known for ${platform}-${arch}`);+ expect(downloads).toEqual([]);+ expect(readdirSync(root)).toEqual([]);+ }+ });++ it.each(['bun-linux-x64.zip', 'uv-x86_64-unknown-linux-gnu.tar.gz'])('parses exact checksum entries for %s', asset => {+ const digest = sha256(Buffer.from('archive'));+ const checksums = `${'a'.repeat(64)} ${asset}.extra\r\n${digest.toUpperCase()} *${asset}\r\n`;+ expect(parseRuntimeChecksum(checksums, asset)).toBe(digest);+ for (const name of [`${asset}.extra`, `${asset}-profile`, `prefix-${asset}`, `folder/${asset}`]) {+ expect(() => parseRuntimeChecksum(`${digest} ${name}\n`, asset)).toThrow('Expected one SHA-256 entry');+ }+ expect(() => parseRuntimeChecksum(`${digest}\n`, asset)).toThrow('Expected one SHA-256 entry');+ expect(() => parseRuntimeChecksum(`${digest} ${asset}\n${digest} ${asset}\n`, asset)).toThrow('found 2');+ });++ it.each(['bun', 'uv'] as const)('%s rejects tampered bytes before trying to open them', async tool => {+ const asset = runtimeReleaseAsset(tool, 'linux', 'x64', 'glibc');+ const { download } = serving(asset, Buffer.from('not even an archive'), `${sha256(archiveFor(asset))} ${asset}\n`);+ await expect(installRuntimeRelease(tool, join(root, tool), download, 'linux', 'x64', 'glibc', runs))+ .rejects.toThrow('it was not opened');+ expect(readdirSync(root)).toEqual([]);+ });++ it.each(['bun', 'uv'] as const)('%s rejects tampered, malformed, or missing checksums without installing', async tool => {+ const asset = runtimeReleaseAsset(tool, 'linux', 'x64', 'glibc');+ const archive = archiveFor(asset);+ for (const checksums of [`${'0'.repeat(64)} ${asset}\n`, `not-a-digest ${asset}\n`, `${sha256(archive)} ${asset}.extra\n`, '']) {+ const { download } = serving(asset, archive, checksums);+ await expect(installRuntimeRelease(tool, join(root, tool), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow();+ expect(readdirSync(root)).toEqual([]);+ }+ });++ it.each(['bun', 'uv'] as const)('%s leaves no files after either download fails', async tool => {+ const asset = runtimeReleaseAsset(tool, 'linux', 'x64', 'glibc');+ for (const failArchive of [false, true]) {+ const download: RuntimeReleaseAssetDownload = async url => {+ if (failArchive && url.endsWith(tool === 'bun' ? 'SHASUMS256.txt' : '.sha256')) {+ return Buffer.from(`${sha256(archiveFor(asset))} ${asset}\n`);+ }+ throw new Error('GET release asset answered HTTP 503');+ };+ await expect(installRuntimeRelease(tool, join(root, tool), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow('HTTP 503');+ expect(readdirSync(root)).toEqual([]);+ }+ });++ it.each(['bun', 'uv'] as const)('%s leaves no binaries after verified but unextractable bytes', async tool => {+ const asset = runtimeReleaseAsset(tool, 'linux', 'x64', 'glibc');+ const { download } = serving(asset, Buffer.from('invalid archive with a matching digest'));+ await expect(installRuntimeRelease(tool, join(root, tool), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow();+ expect(readdirSync(root)).toEqual([]);+ });++ it('rejects a truncated tar member even when its archive checksum matches', async () => {+ const asset = runtimeReleaseAsset('uv', 'linux', 'x64', 'glibc');+ const tar = tarOf({ 'uv-x86_64-unknown-linux-gnu/uv': executable });+ const { download } = serving(asset, gzipSync(tar.subarray(0, 1025)));+ await expect(installRuntimeRelease('uv', join(root, 'uv'), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow('Truncated tar entry');+ expect(readdirSync(root)).toEqual([]);+ });++ it('requires the primary executable and ignores unrelated archive paths', async () => {+ for (const tool of ['bun', 'uv'] as const) {+ const asset = runtimeReleaseAsset(tool, 'linux', 'x64', 'glibc');+ const files = { [`other/${tool}`]: executable };+ const { download } = serving(asset, tool === 'bun' ? zipOf(files) : gzipSync(tarOf(files)));+ await expect(installRuntimeRelease(tool, join(root, tool), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow(`No ${tool} executable`);+ expect(readdirSync(root)).toEqual([]);+ }+ });++ it('rejects duplicate executable entries before writing either one', async () => {+ const asset = runtimeReleaseAsset('bun', 'linux', 'x64', 'glibc');+ const { download } = serving(asset, zipOf({ bun: executable, 'bun-linux-x64/bun': executable }));+ await expect(installRuntimeRelease('bun', join(root, 'bun'), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow('Duplicate bun');+ expect(readdirSync(root)).toEqual([]);+ });++ it('accepts stored ZIP entries as well as deflated ones', async () => {+ const asset = runtimeReleaseAsset('bun', 'linux', 'x64', 'glibc');+ await installRuntimeRelease('bun', join(root, 'bun'), serving(asset, zipOf({ 'bun-linux-x64/bun': executable })).download, 'linux', 'x64', 'glibc', runs);+ expect(readFileSync(join(root, 'bun'))).toEqual(executable);+ });++ it('rejects truncated ZIP data even when the archive checksum matches', async () => {+ const asset = runtimeReleaseAsset('bun', 'linux', 'x64', 'glibc');+ const archive = archiveFor(asset);+ const central = archive.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));+ archive.writeUInt32LE(archive.length, central + 20);+ await expect(installRuntimeRelease('bun', join(root, 'bun'), serving(asset, archive).download, 'linux', 'x64', 'glibc', runs))+ .rejects.toThrow('Truncated ZIP data');+ expect(readdirSync(root)).toEqual([]);+ });++ it('preserves an existing binary when a replacement fails verification', async () => {+ const asset = runtimeReleaseAsset('bun', 'linux', 'x64', 'glibc');+ const destination = join(root, 'bun');+ writeFileSync(destination, 'existing binary');+ const { download } = serving(asset, archiveFor(asset), `${'0'.repeat(64)} ${asset}\n`);+ await expect(installRuntimeRelease('bun', destination, download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow('it was not opened');+ expect(readFileSync(destination, 'utf8')).toBe('existing binary');+ expect(readdirSync(root)).toEqual(['bun']);+ });++ it('installs uv without uvx when the archive omits the companion', async () => {+ const asset = runtimeReleaseAsset('uv', 'linux', 'x64', 'glibc');+ await installRuntimeRelease('uv', join(root, 'uv'), serving(asset, archiveFor(asset, false)).download, 'linux', 'x64', 'glibc', runs);+ expect(readdirSync(root)).toEqual(['uv']);+ });++ it('cleans staging files if moving a binary into place fails', async () => {+ const asset = runtimeReleaseAsset('bun', 'linux', 'x64', 'glibc');+ const destination = join(root, 'bun');+ mkdirSync(destination);+ await expect(installRuntimeRelease('bun', destination, serving(asset).download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow();+ expect(readdirSync(root)).toEqual(['bun']);+ expect(readdirSync(destination)).toEqual([]);+ });++ describe('only installs a build that runs here', () => {+ const bunX64 = 'bun-linux-x64.zip';+ const bunBaseline = 'bun-linux-x64-baseline.zip';+ const base = 'https://github.com/oven-sh/bun/releases/latest/download/';++ function servingBun(assets: Record<string, Buffer>, checksums?: string) {+ const downloads: string[] = [];+ const shasums = checksums ?? Object.entries(assets).map(([name, archive]) => `${sha256(archive)} ${name}`).join('\n') + '\n';+ const download: RuntimeReleaseAssetDownload = async url => {+ downloads.push(url.slice(base.length));+ if (url === `${base}SHASUMS256.txt`) return Buffer.from(shasums);+ const name = url.slice(base.length);+ if (assets[name]) return assets[name];+ throw new Error(`Unexpected download: ${url}`);+ };+ return { download, downloads };+ }++ it('falls back to the baseline build, verified against its own entry, when the x64 build does not run', async () => {+ const baselineBinary = Buffer.from('baseline bun');+ const baselineArchive = zipOf({ 'bun-linux-x64-baseline/bun': baselineBinary });+ const { download, downloads } = servingBun({ [bunX64]: archiveFor(bunX64), [bunBaseline]: baselineArchive });+ const probed: string[] = [];+ const destination = join(root, 'bin', 'bun');++ await installRuntimeRelease('bun', destination, download, 'linux', 'x64', 'glibc', {+ isRosettaTranslated: () => false,+ probeExecutable: path => {+ probed.push(readFileSync(path, 'utf8'));+ expect(dirname(path)).not.toBe(dirname(destination));+ expect(existsSync(destination)).toBe(false);+ return readFileSync(path).equals(baselineBinary);+ },+ });++ expect(readFileSync(destination)).toEqual(baselineBinary);+ expect(probed).toEqual([executable.toString('utf8'), 'baseline bun']);+ expect(downloads).toEqual(['SHASUMS256.txt', bunX64, bunBaseline]);+ expect(readdirSync(dirname(destination))).toEqual(['bun']);+ });++ it('picks the musl baseline on musl Linux', async () => {+ const musl = 'bun-linux-x64-musl.zip';+ const muslBaseline = 'bun-linux-x64-musl-baseline.zip';+ const { download, downloads } = servingBun({ [musl]: archiveFor(musl), [muslBaseline]: archiveFor(muslBaseline) });+ let calls = 0;+ await installRuntimeRelease('bun', join(root, 'bun'), download, 'linux', 'x64', 'musl', {+ isRosettaTranslated: () => false,+ probeExecutable: () => ++calls === 2,+ });+ expect(downloads).toEqual(['SHASUMS256.txt', musl, muslBaseline]);+ expect(runtimeReleaseAsset('bun', 'win32', 'x64', 'glibc', true)).toBe('bun-windows-x64-baseline.zip');+ expect(runtimeReleaseAsset('bun', 'darwin', 'x64', 'glibc', true)).toBe('bun-darwin-x64-baseline.zip');+ expect(() => runtimeReleaseAsset('bun', 'linux', 'arm64', 'glibc', true)).toThrow('No baseline bun');+ expect(() => runtimeReleaseAsset('uv', 'linux', 'x64', 'glibc', true)).toThrow('No baseline uv');+ });++ it('aborts and keeps the existing binary when the baseline build does not run either', async () => {+ const destination = join(root, 'bun');+ writeFileSync(destination, 'existing binary');+ const { download } = servingBun({ [bunX64]: archiveFor(bunX64), [bunBaseline]: archiveFor(bunBaseline) });+ await expect(installRuntimeRelease('bun', destination, download, 'linux', 'x64', 'glibc', {+ isRosettaTranslated: () => false,+ probeExecutable: () => false,+ })).rejects.toThrow(`${bunX64} and ${bunBaseline} verified but \`bun --version\` did not run on this machine; nothing was installed`);+ expect(readFileSync(destination, 'utf8')).toBe('existing binary');+ expect(readdirSync(root)).toEqual(['bun']);+ });++ it('never falls back when the regular build fails verification', async () => {+ const { download, downloads } = servingBun(+ { [bunX64]: archiveFor(bunX64), [bunBaseline]: archiveFor(bunBaseline) },+ `${'0'.repeat(64)} ${bunX64}\n${sha256(archiveFor(bunBaseline))} ${bunBaseline}\n`,+ );+ await expect(installRuntimeRelease('bun', join(root, 'bun'), download, 'linux', 'x64', 'glibc', runs)).rejects.toThrow('it was not opened');+ expect(downloads).toEqual(['SHASUMS256.txt', bunX64]);+ expect(readdirSync(root)).toEqual([]);+ });++ it('rejects a baseline build that fails its own checksum entry', async () => {+ const baselineArchive = archiveFor(bunBaseline);+ const { download } = servingBun(+ { [bunX64]: archiveFor(bunX64), [bunBaseline]: baselineArchive },+ `${sha256(archiveFor(bunX64))} ${bunX64}\n${'0'.repeat(64)} ${bunBaseline}\n`,+ );+ await expect(installRuntimeRelease('bun', join(root, 'bun'), download, 'linux', 'x64', 'glibc', {+ isRosettaTranslated: () => false,+ probeExecutable: () => false,+ })).rejects.toThrow(`${bunBaseline} has SHA-256`);+ expect(readdirSync(root)).toEqual([]);+ });++ it.each([+ ['bun', 'bun-linux-aarch64.zip'],+ ['uv', 'uv-aarch64-unknown-linux-gnu.tar.gz'],+ ['uv', 'uv-x86_64-unknown-linux-gnu.tar.gz'],+ ] as const)('%s aborts without a fallback when %s does not run', async (tool, asset) => {+ const arch = asset.includes('aarch64') ? 'arm64' : 'x64';+ const destination = join(root, tool);+ writeFileSync(destination, 'existing binary');+ const { download, downloads } = serving(asset);+ await expect(installRuntimeRelease(tool, destination, download, 'linux', arch, 'glibc', {+ isRosettaTranslated: () => false,+ probeExecutable: () => false,+ })).rejects.toThrow(`${asset} verified but \`${tool} --version\` did not run on this machine`);+ expect(downloads).toHaveLength(2);+ expect(readFileSync(destination, 'utf8')).toBe('existing binary');+ expect(readdirSync(root)).toEqual([tool]);+ });++ it.each([+ ['bun', 'bun-darwin-aarch64.zip'],+ ['uv', 'uv-aarch64-apple-darwin.tar.gz'],+ ] as const)('installs the native %s build for an x64 process under Rosetta', async (tool, asset) => {+ const { download, downloads } = serving(asset);+ await installRuntimeRelease(tool, join(root, tool), download, 'darwin', 'x64', 'glibc', {+ isRosettaTranslated: () => true,+ probeExecutable: () => true,+ });+ expect(downloads[downloads.length - 1]).toEndWith(`/${asset}`);+ expect(readFileSync(join(root, tool))).toEqual(executable);+ });++ it('only asks about Rosetta for an x64 process on macOS', async () => {+ let asked = 0;+ const isRosettaTranslated = () => { asked++; return true; };+ for (const [platform, arch, asset] of [+ ['linux', 'x64', 'bun-linux-x64.zip'],+ ['win32', 'x64', 'bun-windows-x64.zip'],+ ['darwin', 'arm64', 'bun-darwin-aarch64.zip'],+ ] as const) {+ const { download } = serving(asset);+ await installRuntimeRelease('bun', join(root, platform, 'bun'), download, platform, arch, 'glibc', { isRosettaTranslated, probeExecutable: () => true });+ }+ expect(asked).toBe(0);+ const { download, downloads } = serving('bun-darwin-x64.zip');+ await installRuntimeRelease('bun', join(root, 'native', 'bun'), download, 'darwin', 'x64', 'glibc', { isRosettaTranslated: () => false, probeExecutable: () => true });+ expect(downloads[1]).toEndWith('/bun-darwin-x64.zip');+ });+ });++ it.each(['bun', 'uv'] as const)('%s preserves verification ABORT diagnostics and manual remediation with timers disabled', tool => {+ const source = new URL('../src/npx-cli/install/setup-runtime.ts', import.meta.url).href;+ const toolPaths = new URL('../src/npx-cli/install/tool-path.ts', import.meta.url).href;+ const asset = runtimeReleaseAsset(tool, process.platform, process.arch, 'glibc');+ const result = spawnSync(process.execPath, ['--eval', `+ const { mock } = await import('bun:test');+ const childProcess = await import('node:child_process');+ const actualSpawnSync = childProcess.spawnSync;+ mock.module('child_process', () => ({+ ...childProcess,+ spawnSync: (command, ...args) => command === 'ldd'+ ? { stdout: 'ldd (GNU libc) 2.40', stderr: '', status: 0 }+ : actualSpawnSync(command, ...args),+ }));+ const paths = await import(${JSON.stringify(toolPaths)});+ mock.module(${JSON.stringify(toolPaths)}, () => ({+ ...paths,+ findBunExecutablePath: () => null,+ getToolPath: () => null,+ bunCommonPaths: () => [${JSON.stringify(join(root, 'bin', 'bun'))}],+ }));+ globalThis.fetch = async (url, options) => {+ if (options.signal !== undefined) throw new Error('Expected no download timeout when the override is zero');+ return new Response(+ String(url).endsWith(${JSON.stringify(tool === 'bun' ? 'SHASUMS256.txt' : '.sha256')})+ ? ${JSON.stringify(`${'0'.repeat(64)} ${asset}\n`)}+ : 'unverified archive bytes'+ );+ };+ const runtime = await import(${JSON.stringify(source)});+ try { await runtime.${tool === 'bun' ? 'ensureBun' : 'ensureUv'}(); process.exitCode = 2; }+ catch (error) { console.log(JSON.stringify({ name: error.name, message: error.message, remediation: error.remediation })); }+ `], {+ encoding: 'utf8', timeout: 10_000,+ env: {+ ...process.env,+ CLAUDE_MEM_DATA_DIR: join(root, 'data'),+ CLAUDE_MEM_INSTALL_TIMEOUT_MS: '0',+ UV_INSTALL_DIR: join(root, 'bin'),+ },+ });+ expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' });+ expect(JSON.parse(result.stdout)).toMatchObject({+ name: 'InstallAbortError',+ message: expect.stringContaining('it was not opened'),+ remediation: expect.stringContaining(`Install ${tool === 'bun' ? 'Bun' : 'uv'} manually:`),+ });+ const record = JSON.parse(readFileSync(join(root, 'data', 'last-install-error.json'), 'utf8'));+ expect(record.component).toBe(`${tool}-install`);+ expect(record.remediation).toContain('npx claude-mem install');+ expect(existsSync(join(root, 'bin'))).toBe(false);+ });++ it('contains no piped installer commands in either automatic install path', () => {+ const source = readFileSync(new URL('../src/npx-cli/install/setup-runtime.ts', import.meta.url), 'utf8');+ for (const name of ['runBunInstaller', 'runUvInstaller']) {+ const start = source.indexOf(`async function ${name}(`);+ expect(start).toBeGreaterThan(0);+ const body = source.slice(start, source.indexOf('\n}\n', start));+ expect(body).toContain('await installRuntimeRelease(');+ expect(body).not.toMatch(/curl|powershell|\biex\b|\|\s*(?:ba)?sh|execSync/);+ }+ expect(source).not.toMatch(/execSync\(/);+ });+});+describe('ensureBun validates the installer runtime', () => {let root: string;