Skip to content

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

56.6 KB
Raw Blame
import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test';
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';
import { delimiter, dirname, join } from 'path';
import { tmpdir } from 'os';
import { gzipSync } from 'zlib';
import {
  readInstallMarker,
  writeInstallMarker,
  isInstallCurrent,
  bunCommonPaths,
  uvCommonPaths,
  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';
import { ErrorSeverity } from '../src/npx-cli/install/error-taxonomy';
import { IS_WINDOWS } from '../src/npx-cli/utils/paths';

function probeBunVersion(): string | null {
  try {
    const result = spawnSync('bun', ['--version'], {
      encoding: 'utf-8',
      stdio: ['pipe', 'pipe', 'pipe'],
    });
    return result.status === 0 ? result.stdout.trim() : null;
  } catch {
    return null;
  }
}

describe('setup-runtime install marker', () => {
  let tempDir: string;

  beforeEach(() => {
    tempDir = join(
      tmpdir(),
      `setup-runtime-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
    );
    mkdirSync(tempDir, { recursive: true });
  });

  afterEach(() => {
    try {
      rmSync(tempDir, { recursive: true, force: true });
    } catch {
      // Ignore cleanup errors
    }
  });

  describe('readInstallMarker', () => {
    it('returns null when marker file is missing', () => {
      expect(readInstallMarker(tempDir)).toBeNull();
    });

    it('returns null when marker file is invalid JSON', () => {
      writeFileSync(join(tempDir, '.install-version'), 'not valid json');
      expect(readInstallMarker(tempDir)).toBeNull();
    });

    it('returns parsed marker when file is valid', () => {
      writeInstallMarker(tempDir, '1.2.3', '1.0.0', '0.5.0');
      const marker = readInstallMarker(tempDir);
      expect(marker).not.toBeNull();
      expect(marker?.version).toBe('1.2.3');
      expect(marker?.bun).toBe('1.0.0');
      expect(marker?.uv).toBe('0.5.0');
    });

    it('returns parsed marker when file is a legacy plain-text version', () => {
      writeFileSync(join(tempDir, '.install-version'), '12.4.4\n');
      const marker = readInstallMarker(tempDir);
      expect(marker).toEqual({ version: '12.4.4' });
    });

    it('normalizes a leading v in legacy plain-text versions', () => {
      writeFileSync(join(tempDir, '.install-version'), 'v12.4.4\n');
      const marker = readInstallMarker(tempDir);
      expect(marker).toEqual({ version: '12.4.4' });
    });
  });

  describe('writeInstallMarker', () => {
    it('writes a JSON file with the canonical schema { version, bun, uv, installedAt }', () => {
      writeInstallMarker(tempDir, '12.4.7', '1.2.0', '0.4.18');

      const path = join(tempDir, '.install-version');
      expect(existsSync(path)).toBe(true);

      const parsed = JSON.parse(readFileSync(path, 'utf-8'));
      expect(parsed.version).toBe('12.4.7');
      expect(parsed.bun).toBe('1.2.0');
      expect(parsed.uv).toBe('0.4.18');
      expect(typeof parsed.installedAt).toBe('string');
      expect(() => new Date(parsed.installedAt).toISOString()).not.toThrow();
    });

    it('only writes the four documented fields', () => {
      writeInstallMarker(tempDir, '1.0.0', '1.0.0', '0.1.0');
      const parsed = JSON.parse(readFileSync(join(tempDir, '.install-version'), 'utf-8'));
      expect(Object.keys(parsed).sort()).toEqual(['bun', 'installedAt', 'uv', 'version'].sort());
    });
  });

  describe('isInstallCurrent', () => {
    it('returns false when node_modules is missing', () => {
      writeInstallMarker(tempDir, '1.0.0', '1.0.0', '0.1.0');
      expect(isInstallCurrent(tempDir, '1.0.0')).toBe(false);
    });

    it('returns false when marker is missing (but node_modules exists)', () => {
      mkdirSync(join(tempDir, 'node_modules'));
      expect(isInstallCurrent(tempDir, '1.0.0')).toBe(false);
    });

    it('returns false when marker version does not match expected', () => {
      mkdirSync(join(tempDir, 'node_modules'));
      const bunVersion = probeBunVersion() ?? '1.0.0';
      writeInstallMarker(tempDir, '1.0.0', bunVersion, '0.1.0');
      expect(isInstallCurrent(tempDir, '2.0.0')).toBe(false);
    });

    it('returns true when marker matches version and bun version matches', () => {
      const bunVersion = probeBunVersion();
      if (!bunVersion) {
        return;
      }
      mkdirSync(join(tempDir, 'node_modules'));
      writeInstallMarker(tempDir, '1.0.0', bunVersion, '0.1.0');
      expect(isInstallCurrent(tempDir, '1.0.0')).toBe(true);
    });

    it('returns false for a matching legacy plain-text marker when bun is available', () => {
      const bunVersion = probeBunVersion();
      if (!bunVersion) {
        return;
      }
      mkdirSync(join(tempDir, 'node_modules'));
      writeFileSync(join(tempDir, '.install-version'), '1.0.0\n');
      expect(isInstallCurrent(tempDir, '1.0.0')).toBe(false);
    });
  });
});

describe('setup-runtime binary detection honours installer env vars', () => {
  const bunName = IS_WINDOWS ? 'bun.exe' : 'bun';
  const uvName = IS_WINDOWS ? 'uv.exe' : 'uv';

  it('bunCommonPaths honours BUN_INSTALL', () => {
    const paths = bunCommonPaths({ BUN_INSTALL: '/opt/bun' });
    expect(paths).toContain(join('/opt/bun', 'bin', bunName));
  });

  it('uvCommonPaths honours UV_INSTALL_DIR', () => {
    const paths = uvCommonPaths({ UV_INSTALL_DIR: '/opt/uv/bin' });
    expect(paths).toContain(join('/opt/uv/bin', uvName));
  });

  it('uvCommonPaths honours XDG_BIN_HOME', () => {
    const paths = uvCommonPaths({ XDG_BIN_HOME: '/xdg/bin' });
    expect(paths).toContain(join('/xdg/bin', uvName));
  });

  it('bunCommonPaths returns absolute paths and no duplicates', () => {
    const paths = bunCommonPaths({ BUN_INSTALL: '/opt/bun' });
    expect(paths.length).toBe(new Set(paths).size);
    expect(paths.every(p => p.length > 0)).toBe(true);
  });
});

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;

  beforeEach(() => {
    root = mkdtempSync(join(tmpdir(), 'bun-installer-version-'));
  });

  afterEach(() => {
    rmSync(root, { recursive: true, force: true });
  });

  function checkBunVersion(version: string) {
    const executable = join(root, IS_WINDOWS ? 'bun.cmd' : 'bun');
    writeFileSync(executable, IS_WINDOWS
      ? `@echo off\r\necho ${version}\r\n`
      : `#!/bin/sh\nprintf '${version}\\n'\n`);
    if (!IS_WINDOWS) chmodSync(executable, 0o755);
    const source = new URL('../src/npx-cli/install/setup-runtime.ts', import.meta.url).href;
    return spawnSync(process.execPath, ['--eval', `
      const { ensureBun } = await import(${JSON.stringify(source)});
      try { console.log(JSON.stringify(await ensureBun())); }
      catch (error) { console.error(error.message); process.exitCode = 1; }
    `], {
      encoding: 'utf8', timeout: 10_000,
      env: {
        ...process.env,
        PATH: [root, process.env.PATH].filter(Boolean).join(delimiter),
        CLAUDE_MEM_DATA_DIR: join(root, 'data'),
      },
    });
  }

  it.each(['1.1.42', '1.2.15'])('rejects Bun %s before dependency installation and explains the upgrade', version => {
    const result = checkBunVersion(version);
    expect(result.status).toBe(1);
    expect(result.stderr).toContain(`Bun ${version}`);
    const error = JSON.parse(readFileSync(join(root, 'data', 'last-install-error.json'), 'utf8'));
    expect(error.cause).toContain('older than 1.2.16');
    expect(error.remediation).toContain('bun upgrade');
  });

  it('accepts the existing launcher minimum', () => {
    const result = checkBunVersion('1.2.16');
    expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' });
    expect(JSON.parse(result.stdout).version).toBe('1.2.16');
    expect(existsSync(join(root, 'data', 'last-install-error.json'))).toBe(false);
  });
});

describe('installPluginDependencies passes the bun path as an argument, not through a shell', () => {
  // The bun path now flows from installer env vars (e.g. $BUN_INSTALL) that can
  // hold spaces or shell metacharacters. execFile must pass it as argv[0] so it
  // never reaches a shell.
  it('runs a bun path containing spaces and injection syntax without evaluating it', async () => {
    if (IS_WINDOWS) return; // POSIX fake-bin shell script

    const unique = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
    const marker = join(tmpdir(), `pwned-${unique}`);
    // The bun executable lives in a dir whose name has a space and injection
    // syntax; its output goes to a clean path so the fake script's own redirect
    // is never the thing under test.
    const base = join(tmpdir(), `bun space $(touch ${marker}) ${unique}`);
    const targetDir = join(base, 'target');
    const argsFile = join(tmpdir(), `args-${unique}.txt`);
    mkdirSync(targetDir, { recursive: true });
    writeFileSync(join(targetDir, 'package.json'), JSON.stringify({ dependencies: {} }));

    const fakeBun = join(base, 'bun');
    writeFileSync(fakeBun, `#!/bin/sh\nprintf '%s\\n' "$@" > "${argsFile}"\nexit 0\n`);
    chmodSync(fakeBun, 0o755);

    try {
      await installPluginDependencies(targetDir, fakeBun);
      const recorded = readFileSync(argsFile, 'utf-8').trim().split('\n');
      expect(recorded).toEqual(['install', '--frozen-lockfile', '--ignore-scripts', '--filter', 'claude-mem-plugin']);
      // The $(touch ...) in the path must NOT have executed.
      expect(existsSync(marker)).toBe(false);
    } finally {
      rmSync(base, { recursive: true, force: true });
      rmSync(marker, { force: true });
      rmSync(argsFile, { force: true });
    }
  });
});

describe('ensureServerEmbedder', () => {
  // The plugin install omits the optional embedder; a server start installs it.
  function fakePluginRoot() {
    const root = mkdtempSync(join(tmpdir(), 'cm-embedder-'));
    const argsFile = join(root, 'args.txt');
    writeFileSync(join(root, 'package.json'), JSON.stringify({ dependencies: {} }));
    const fakeBun = join(root, 'bun');
    writeFileSync(fakeBun, `#!/bin/sh\nprintf '%s\\n' "$@" > "${argsFile}"\nexit 0\n`);
    chmodSync(fakeBun, 0o755);
    return { root, argsFile, fakeBun };
  }

  it('installs optional dependencies when the embedder is missing', async () => {
    if (IS_WINDOWS) return; // POSIX fake-bin shell script
    const { root, argsFile, fakeBun } = fakePluginRoot();
    try {
      await ensureServerEmbedder(root, fakeBun);
      expect(readFileSync(argsFile, 'utf-8').trim().split('\n')).toEqual(['install', '--frozen-lockfile', '--ignore-scripts']);
    } finally {
      rmSync(root, { recursive: true, force: true });
    }
  });

  it('runs no install when the embedder is present', async () => {
    if (IS_WINDOWS) return;
    const { root, argsFile, fakeBun } = fakePluginRoot();
    try {
      mkdirSync(join(root, 'node_modules', '@huggingface', 'transformers'), { recursive: true });
      writeFileSync(join(root, 'node_modules', '@huggingface', 'transformers', 'package.json'), '{}');
      await ensureServerEmbedder(root, fakeBun);
      expect(existsSync(argsFile)).toBe(false);
    } finally {
      rmSync(root, { recursive: true, force: true });
    }
  });
});

// #2910: every installer path suppresses lifecycle scripts, so tree-sitter-cli's
// install.js (the step that downloads the executable) never ran and smart_search
// silently returned 0 symbols. The installer now runs that one trusted,
// package-local script when the CLI is not usable.
describe('tree-sitter CLI provisioning (#2910)', () => {
  const TREE_SITTER_BINARY_NAME = process.platform === 'win32' ? 'tree-sitter.exe' : 'tree-sitter';
  const TREE_SITTER_INSTALL_TIMEOUT_MS = 30_000;
  const REPO_TREE_SITTER_BINARY = join(import.meta.dir, '..', 'node_modules', 'tree-sitter-cli', TREE_SITTER_BINARY_NAME);
  let tempDir: string;
  let previousDataDir: string | undefined;
  let previousPath: string | undefined;

  beforeEach(() => {
    tempDir = mkdtempSync(join(tmpdir(), 'tree-sitter-provision-'));
    previousPath = process.env.PATH;
    // Hide any tree-sitter already on this machine's PATH, but keep node reachable for `#!/usr/bin/env node` fixtures.
    process.env.PATH = (previousPath ?? '').split(delimiter).filter(dir => dir && !existsSync(join(dir, TREE_SITTER_BINARY_NAME))).join(delimiter);
    previousDataDir = process.env.CLAUDE_MEM_DATA_DIR;
    process.env.CLAUDE_MEM_DATA_DIR = join(tempDir, 'data');
  });

  afterEach(() => {
    if (previousDataDir === undefined) delete process.env.CLAUDE_MEM_DATA_DIR;
    else process.env.CLAUDE_MEM_DATA_DIR = previousDataDir;
    if (previousPath === undefined) delete process.env.PATH;
    else process.env.PATH = previousPath;
    rmSync(tempDir, { recursive: true, force: true });
  });

  function writeCliPackage(installScript?: string): string {
    const cliDir = join(tempDir, 'node_modules', 'tree-sitter-cli');
    mkdirSync(cliDir, { recursive: true });
    writeFileSync(join(cliDir, 'package.json'), JSON.stringify({ name: 'tree-sitter-cli', version: '0.26.9', bin: { 'tree-sitter': 'tree-sitter' } }));
    if (installScript !== undefined) writeFileSync(join(cliDir, 'install.js'), installScript);
    return cliDir;
  }

  function writeCliBinary(cliDir: string): void {
    const target = join(cliDir, TREE_SITTER_BINARY_NAME);
    writeFileSync(target, fixtureBinary());
    if (process.platform !== 'win32') chmodSync(target, 0o755);
  }

  const fixtureBinary = (): Buffer => process.platform === 'win32'
    ? readFileSync(REPO_TREE_SITTER_BINARY)
    : Buffer.from("#!/bin/sh\nprintf 'tree-sitter 0.26.9\\n'\n");

  // Like tree-sitter-cli's real install.js, these write the executable into
  // their working directory, which is a staging directory inside the package.
  const materializingInstallScript = (): string => [
    `const fs = require('fs');`,
    `const target = require('path').join(process.cwd(), ${JSON.stringify(TREE_SITTER_BINARY_NAME)});`,
    `fs.writeFileSync(target, Buffer.from(${JSON.stringify(fixtureBinary().toString('base64'))}, 'base64'));`,
    process.platform === 'win32' ? '' : 'fs.chmodSync(target, 0o755);',
  ].join('\n');

  const partialDownloadScript = (exitStatement: string): string => [
    `require('fs').writeFileSync(require('path').join(process.cwd(), ${JSON.stringify(TREE_SITTER_BINARY_NAME)}), 'half a download');`,
    exitStatement,
  ].join('\n');

  const sha256 = (content: string | Buffer) => createHash('sha256').update(content).digest('hex');
  const pinFixtureBinary = () => sha256(fixtureBinary());
  // The dev dependency can be newer than the pinned release; only a pinned
  // binary counts as "already works" now that the digest is checked first.
  const repoBinaryIsPinned = (): boolean => {
    try {
      const version = JSON.parse(readFileSync(join(dirname(REPO_TREE_SITTER_BINARY), 'package.json'), 'utf-8')).version;
      return pinnedTreeSitterExecutableSha256(version) === sha256(readFileSync(REPO_TREE_SITTER_BINARY));
    } catch {
      return false;
    }
  };

  function expectNothingLeftInPlace(cliDir: string): void {
    expect(existsSync(treeSitterCliBinaryPath(tempDir))).toBe(false);
    expect(readdirSync(cliDir).filter(entry => entry.startsWith('.provision-'))).toEqual([]);
  }

  // Stands in for the direct download of the release asset, so no test reaches
  // the network; `downloads` lists every URL asked for.
  function releaseAssetServing(answer: () => Buffer) {
    const downloads: string[] = [];
    const download = async (url: string): Promise<Buffer> => {
      downloads.push(url);
      return answer();
    };
    return { download, downloads };
  }
  const releaseAssetUnavailable = () => releaseAssetServing(() => {
    throw new Error('GET release asset answered HTTP 503');
  });

  it('runs the package install script when the executable is missing', async () => {
    const cliDir = writeCliPackage(materializingInstallScript());

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary)).resolves.toBe('release');
    expect(existsSync(treeSitterCliBinaryPath(tempDir))).toBe(true);
    expect(readdirSync(cliDir).filter(entry => entry.startsWith('.provision-'))).toEqual([]);
  });

  // The File Read Gate and the parser only check that the executable exists, so
  // a half-written one would send Claude to smart_outline, which cannot parse.
  it('leaves no executable in place when the download fails partway and the direct download fails too', async () => {
    const cliDir = writeCliPackage(partialDownloadScript('process.exitCode = 2;'));
    const { download, downloads } = releaseAssetUnavailable();

    const provisioning = ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, download);
    // The install script's own error, with the direct download's reason added.
    await expect(provisioning).rejects.toMatchObject({ code: 2 });
    await expect(provisioning).rejects.toThrow('Downloading the release asset directly failed too: GET release asset answered HTTP 503');
    expect(downloads).toEqual([treeSitterReleaseAssetUrl('0.26.9')!]);
    expectNothingLeftInPlace(cliDir);
  });

  // The timeout is one budget for both attempts: a script that used it up gets
  // no second download on top.
  it('leaves no executable in place when the download is killed by the timeout', async () => {
    const cliDir = writeCliPackage(partialDownloadScript('setTimeout(() => {}, 5000);'));
    const { download, downloads } = releaseAssetServing(() => gzipSync(fixtureBinary()));

    await expect(ensureTreeSitterCliBinary(tempDir, 100, pinFixtureBinary, undefined, download)).rejects.toMatchObject({ killed: true });
    expect(downloads).toEqual([]);
    expectNothingLeftInPlace(cliDir);
  });

  // tree-sitter-cli's install.js turns keep-alive off and has no error handler:
  // on some networks its request is reset every time ("socket hang up") while a
  // plain fetch of the same asset succeeds.
  it('downloads the release asset directly when the install script fails', async () => {
    const cliDir = writeCliPackage("console.error('Error: socket hang up'); process.exitCode = 1;");
    const { download, downloads } = releaseAssetServing(() => gzipSync(fixtureBinary()));

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, download)).resolves.toBe('release');
    expect(downloads).toEqual([treeSitterReleaseAssetUrl('0.26.9')!]);
    expect(sha256(readFileSync(treeSitterCliBinaryPath(tempDir)))).toBe(pinFixtureBinary());
    expect(await isTreeSitterCliBinaryUsable(tempDir)).toBe(true);
    expect(readdirSync(cliDir).filter(entry => entry.startsWith('.provision-'))).toEqual([]);
  });

  // install.js can also exit 0 after the connection drops mid-transfer, leaving
  // a truncated executable.
  it('downloads the release asset directly when the install script exits 0 on a truncated executable', async () => {
    writeCliPackage(partialDownloadScript(''));
    const { download, downloads } = releaseAssetServing(() => gzipSync(fixtureBinary()));

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, download)).resolves.toBe('release');
    expect(downloads).toHaveLength(1);
    expect(sha256(readFileSync(treeSitterCliBinaryPath(tempDir)))).toBe(pinFixtureBinary());
  });

  it('does not download directly when the install script delivers the pinned executable', async () => {
    writeCliPackage(materializingInstallScript());
    const { download, downloads } = releaseAssetServing(() => gzipSync(fixtureBinary()));

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, download)).resolves.toBe('release');
    expect(downloads).toEqual([]);
  });

  // The direct download gets no more trust than install.js: the pinned digest
  // decides, before anything runs.
  it.skipIf(process.platform === 'win32')('refuses, without running it, a directly downloaded executable whose SHA-256 is not the pinned one', async () => {
    const ranMarker = join(tempDir, 'direct-download-ran');
    const cliDir = writeCliPackage("console.error('Error: socket hang up'); process.exitCode = 1;");
    const { download } = releaseAssetServing(() => gzipSync(Buffer.from(`#!/bin/sh\ntouch '${ranMarker}'\necho 'tree-sitter 0.26.9'\n`)));

    const provisioning = ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, download);
    await expect(provisioning).rejects.toMatchObject({ code: 1 });
    await expect(provisioning).rejects.toThrow(/directly failed too: .* not the pinned [0-9a-f]{64}; it was not run/);
    expect(existsSync(ranMarker)).toBe(false);
    expectNothingLeftInPlace(cliDir);
  });

  it('leaves no executable in place when the direct download is not a gzip stream', async () => {
    const cliDir = writeCliPackage("console.error('Error: socket hang up'); process.exitCode = 1;");
    const { download } = releaseAssetServing(() => gzipSync(fixtureBinary()).subarray(0, 12));

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, download))
      .rejects.toThrow('Downloading the release asset directly failed too');
    expectNothingLeftInPlace(cliDir);
  });

  it('never moves an executable that does not answer --version into place', async () => {
    const cliDir = writeCliPackage(partialDownloadScript(''));

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, () => sha256('half a download')))
      .rejects.toThrow('matches the pinned SHA-256 but cannot run on this system');
    expectNothingLeftInPlace(cliDir);
  });

  // A replaced release asset must never run, not even for the --version probe.
  it.skipIf(process.platform === 'win32')('refuses, without running it, an executable whose SHA-256 is not the pinned one', async () => {
    const ranMarker = join(tempDir, 'downloaded-executable-ran');
    const cliDir = writeCliPackage([
      `const target = require('path').join(process.cwd(), 'tree-sitter');`,
      `require('fs').writeFileSync(target, ${JSON.stringify(`#!/bin/sh
touch '${ranMarker}'
echo 'tree-sitter 0.26.9'
`)});`,
      `require('fs').chmodSync(target, 0o755);`,
    ].join('\n'));

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, pinFixtureBinary, undefined, releaseAssetUnavailable().download))
      .rejects.toThrow('not the pinned');
    expect(existsSync(ranMarker)).toBe(false);
    expectNothingLeftInPlace(cliDir);
  });

  it('downloads nothing when no SHA-256 is pinned for the package version', async () => {
    const downloadMarker = join(tempDir, 'install-script-ran');
    const cliDir = writeCliPackage(`require('fs').writeFileSync(${JSON.stringify(downloadMarker)}, '');`);

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, () => undefined)).rejects.toThrow('No SHA-256 is pinned');
    expect(existsSync(downloadMarker)).toBe(false);
    expectNothingLeftInPlace(cliDir);
  });

  it.skipIf(process.platform === 'win32')('closes stdin before accepting a package-local version response', async () => {
    const cliDir = writeCliPackage();
    const binaryPath = join(cliDir, 'tree-sitter');
    const script = [
      '#!/usr/bin/env node',
      "process.stdin.resume(); process.stdin.on('end', () => process.stdout.write('tree-sitter 0.26.8\\n'));",
    ].join('\n');
    writeFileSync(binaryPath, script);
    chmodSync(binaryPath, 0o755);

    const startedAt = Date.now();
    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS, () => sha256(script))).resolves.toBe('already-usable');
    expect(Date.now() - startedAt).toBeLessThan(2000);
  });

  it('never borrows a tree-sitter package from an ancestor node_modules', async () => {
    writeCliBinary(writeCliPackage());

    await expect(ensureTreeSitterCliBinary(join(tempDir, 'nested', 'cache'), TREE_SITTER_INSTALL_TIMEOUT_MS)).rejects.toThrow('install script not found');
  });

  it('rejects a tree-sitter package path that is not a directory', async () => {
    mkdirSync(join(tempDir, 'node_modules'), { recursive: true });
    writeFileSync(join(tempDir, 'node_modules', 'tree-sitter-cli'), 'not a directory');

    await expect(ensureTreeSitterCliBinary(tempDir, TREE_SITTER_INSTALL_TIMEOUT_MS)).rejects.toThrow('package path is not a directory');
  });

  it('install: a provisioning failure only warns, so the install still reaches sign-in', async () => {
    writeCliPackage("console.error('release asset unavailable'); process.exitCode = 2;");
    const summary = createInstallSummary();

    await expect(provisionTreeSitterCli(tempDir, ErrorSeverity.WARN_CONTINUE, summary, undefined, releaseAssetUnavailable().download)).resolves.toBe(false);

    expect(summary.warnings).toEqual([
      expect.objectContaining({
        component: 'tree-sitter-cli-cache',
        remediation: expect.stringContaining('npx claude-mem repair'),
      }),
    ]);
    expect(existsSync(join(tempDir, 'data', 'last-install-error.json'))).toBe(false);
  });

  it('repair: a provisioning failure aborts and keeps the provisioner output', async () => {
    writeCliPackage([
      "console.log('Downloading https://example/tree-sitter');",
      "console.error('release asset unavailable');",
      'process.exitCode = 2;',
    ].join('\n'));

    let caught: unknown = null;
    try {
      await provisionTreeSitterCli(tempDir, ErrorSeverity.ABORT, createInstallSummary(), undefined, releaseAssetUnavailable().download);
    } catch (error) {
      caught = error;
    }

    expect(caught).toBeInstanceOf(InstallAbortError);
    expect(caught).toMatchObject({
      category: { id: 'tree-sitter-cli-cache-provisioning-failed' },
      cause: { code: 2 },
    });
    const record = JSON.parse(readFileSync(join(tempDir, 'data', 'last-install-error.json'), 'utf-8'));
    expect(record.details).toContain('Downloading https://example/tree-sitter');
    expect(record.details).toContain('release asset unavailable');
    // Both attempts are on record, so the reader can tell a network problem from a bad asset.
    expect(record.details).toContain('Downloading the release asset directly failed too: GET release asset answered HTTP 503');
  });

  it('repair: reports a provisioner that runs past the install timeout', async () => {
    writeCliPackage('setTimeout(() => {}, 5000);');

    let caught: unknown = null;
    try {
      await provisionTreeSitterCli(tempDir, ErrorSeverity.ABORT, createInstallSummary(), 100);
    } catch (error) {
      caught = error;
    }

    expect(caught).toMatchObject({ cause: { killed: true } });
  });

  it.skipIf(process.platform === 'win32')('uses a compatible PATH CLI without running the package installer', async () => {
    writeCliPackage('process.exitCode = 2;');
    const binDir = join(tempDir, 'bin');
    mkdirSync(binDir);
    writeFileSync(join(binDir, TREE_SITTER_BINARY_NAME), "#!/bin/sh\nprintf 'tree-sitter 0.26.9\\n'\n", { mode: 0o755 });
    const oldPath = process.env.PATH;
    process.env.PATH = binDir + delimiter + (oldPath ?? '');
    try {
      await expect(provisionTreeSitterCli(tempDir, ErrorSeverity.ABORT, createInstallSummary())).resolves.toBe(true);
      expect(existsSync(treeSitterCliBinaryPath(tempDir))).toBe(false);
    } finally {
      if (oldPath === undefined) delete process.env.PATH;
      else process.env.PATH = oldPath;
    }
  });

  it.skipIf(process.platform === 'win32')('install and repair skip probes of unpinned package files, even through PATH', async () => {
    const cliDir = writeCliPackage('process.exitCode = 2;');
    const packageBinary = treeSitterCliBinaryPath(tempDir);
    const packageEntry = join(cliDir, 'cli.js');
    for (const path of [packageBinary, packageEntry]) {
      writeFileSync(path, Buffer.from([0]), { mode: 0o755 });
    }
    const binDir = join(tempDir, 'node_modules', '.bin');
    mkdirSync(binDir);
    symlinkSync(packageEntry, join(binDir, TREE_SITTER_BINARY_NAME));
    process.env.PATH = [cliDir, binDir, process.env.PATH].join(delimiter);
    const { download, downloads } = releaseAssetUnavailable();
    const syncProbe = spyOn(childProcess, 'execFileSync').mockImplementation(() => {
      throw new Error('unexpected tree-sitter version probe');
    });
    const execFile = childProcess.execFile;
    const asyncExec = spyOn(childProcess, 'execFile').mockImplementation((...args) => {
      if (Array.isArray(args[1]) && args[1][0] === '--version') {
        throw new Error('unexpected tree-sitter version probe');
      }
      return execFile(...args);
    });
    try {
      await expect(provisionTreeSitterCli(tempDir, ErrorSeverity.WARN_CONTINUE, createInstallSummary(), undefined, download)).resolves.toBe(false);
      // Simulate a missing binary: PATH still must not run the package's shim.
      rmSync(packageBinary);
      process.env.PATH = [binDir, process.env.PATH].join(delimiter);
      await expect(provisionTreeSitterCli(tempDir, ErrorSeverity.ABORT, createInstallSummary(), undefined, download)).rejects.toBeInstanceOf(InstallAbortError);
      expect(downloads).toEqual([treeSitterReleaseAssetUrl('0.26.9')!, treeSitterReleaseAssetUrl('0.26.9')!]);
      expect(syncProbe).not.toHaveBeenCalled();
      expect(asyncExec.mock.calls.some(([, args]) => Array.isArray(args) && args[0] === '--version')).toBe(false);
    } finally {
      syncProbe.mockRestore();
      asyncExec.mockRestore();
    }
  });

  it.skipIf(!repoBinaryIsPinned())('reports nothing when the CLI already works', async () => {
    const cliDir = writeCliPackage();
    copyFileSync(REPO_TREE_SITTER_BINARY, join(cliDir, TREE_SITTER_BINARY_NAME));
    if (process.platform !== 'win32') chmodSync(join(cliDir, TREE_SITTER_BINARY_NAME), 0o755);
    const summary = createInstallSummary();

    await expect(provisionTreeSitterCli(tempDir, ErrorSeverity.ABORT, summary)).resolves.toBe(true);
    expect(summary.warnings).toEqual([]);
  });
});