Skip to content

Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.

49.2 KB
Raw Blame
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import fsSync, { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { after, before, describe, it } from "node:test";
import { pathToFileURL } from "node:url";
import { UPDATER_RUNTIME_FILES } from "../src/utils/updater-core.js";

const INSTALL_SCRIPT = path.resolve(process.cwd(), "scripts", "install.mjs");
const IS_WIN = process.platform === "win32";
const SHELL_RC_FILES = [
  ".bashrc",
  ".bash_profile",
  ".profile",
  ".zshrc",
  ".zprofile",
  ".zshenv",
];

interface ShimHelpers {
  getDefaultBinShimDirs: () => string[];
  inspectBinShim: (
    binDir: string,
    spec: { name: string; relTarget: string },
  ) => Promise<{
    status: string;
    owned: boolean;
    kind: string | null;
    targetPath: string | null;
    pluginDir: string | null;
  }>;
  isInsideNodeModules: (targetPath: string) => boolean;
  parseShimWrapper: (content: string) => {
    hasMarker: boolean;
    targetPath: string | null;
  };
  renderPosixShimWrapper: (targetScriptPath: string) => string;
  renderWindowsCmdShim: (targetScriptPath: string) => string;
  writeFileAtomically: (
    filePath: string,
    content: string,
    mode?: number | null,
    fsOps?: typeof fs,
  ) => Promise<void>;
}

let helpers: ShimHelpers;

function shimFileName(base: string): string {
  return IS_WIN ? `${base}.cmd` : base;
}

function findExecutableDir(cmdName: string): string | null {
  const rawPath = process.env.PATH || (IS_WIN ? process.env.Path || "" : "");
  const exts = IS_WIN ? [".exe", ".cmd", ".bat", ""] : [""];
  for (const rawEntry of rawPath.split(path.delimiter)) {
    const entry = rawEntry.trim().replace(/^"(.*)"$/, "$1");
    if (!entry) continue;
    for (const ext of exts) {
      const candidate = path.join(entry, `${cmdName}${ext}`);
      try {
        if (fsSync.statSync(candidate).isFile()) {
          return entry;
        }
      } catch {
        // continue
      }
    }
  }
  return null;
}

const GIT_BIN_DIR = findExecutableDir("git");

function makeIsolatedEnv(
  homeDir: string,
  extraPathEntries: string[] = [],
  extra: Record<string, string | undefined> = {},
): NodeJS.ProcessEnv {
  const nodeDir = path.dirname(process.execPath);
  const systemDirs = IS_WIN
    ? [process.env.SystemRoot ? path.join(process.env.SystemRoot, "System32") : "C:\\Windows\\System32"]
    : ["/usr/bin", "/bin"];
  const pathParts = [...extraPathEntries, nodeDir, GIT_BIN_DIR, ...systemDirs].filter(
    (p): p is string => Boolean(p),
  );
  const env: NodeJS.ProcessEnv = {
    ...process.env,
    HOME: homeDir,
    USERPROFILE: homeDir,
    PATH: pathParts.join(path.delimiter),
  };
  delete env.GEMINI_HOME;
  delete env.ANTIGRAVITY_APP_DATA_DIR;
  delete env.AGY_FAST_TOOLS;
  delete env.AGY_FAST_REPO;
  delete env.AGY_FAST_CACHE_DIR;
  if (IS_WIN) {
    delete env.Path;
    const drive = path.parse(homeDir).root.replace(/[\\/]+$/, "");
    env.HOMEDRIVE = drive;
    env.HOMEPATH = homeDir.slice(drive.length);
  }
  for (const [k, v] of Object.entries(extra)) {
    if (v === undefined) delete env[k];
    else env[k] = v;
  }
  return env;
}

function runInstaller(
  args: string[],
  env: NodeJS.ProcessEnv,
): { status: number; stdout: string; stderr: string } {
  const res = spawnSync(process.execPath, [INSTALL_SCRIPT, ...args], {
    env,
    encoding: "utf8",
    windowsHide: true,
  });
  return {
    status: res.status ?? 1,
    stdout: res.stdout ?? "",
    stderr: res.stderr ?? "",
  };
}

function runShimCommand(
  command: string,
  args: string[],
  env: NodeJS.ProcessEnv,
  cmdExtraFlags: string[] = [],
): { status: number; stdout: string; stderr: string } {
  if (IS_WIN) {
    const quoteWin = (s: string) => `"${s.replace(/"/g, '""')}"`;
    const cmdLine = [quoteWin(command), ...args.map(quoteWin)].join(" ");
    const res = spawnSync(
      process.env.ComSpec || "cmd.exe",
      [...cmdExtraFlags, "/d", "/s", "/c", `"${cmdLine}"`],
      {
        env,
        encoding: "utf8",
        windowsHide: true,
        windowsVerbatimArguments: true,
      },
    );
    if (res.error) {
      throw res.error;
    }
    return {
      status: res.status ?? 1,
      stdout: res.stdout ?? "",
      stderr: res.stderr ?? "",
    };
  }
  const res = spawnSync(command, args, {
    env,
    encoding: "utf8",
    windowsHide: true,
  });
  if (res.error) {
    throw res.error;
  }
  return {
    status: res.status ?? 1,
    stdout: res.stdout ?? "",
    stderr: res.stderr ?? "",
  };
}

function gitSync(cwd: string, args: string[]): string {
  return execFileSync("git", args, {
    cwd,
    encoding: "utf8",
    stdio: ["ignore", "pipe", "pipe"],
  });
}

async function createLocalTagRepo(rootDir: string, tagVersion: string): Promise<string> {
  const repoRoot = process.cwd();
  const bareDir = path.join(rootDir, `bare-${tagVersion}.git`);
  const workDir = path.join(rootDir, `work-${tagVersion}`);
  await fs.mkdir(bareDir, { recursive: true });
  await fs.mkdir(workDir, { recursive: true });
  gitSync(bareDir, ["init", "--bare"]);
  gitSync(workDir, ["init", "-b", "main"]);
  gitSync(workDir, ["config", "user.name", "Test User"]);
  gitSync(workDir, ["config", "user.email", "[email protected]"]);
  gitSync(workDir, ["config", "commit.gpgsign", "false"]);
  gitSync(workDir, ["config", "tag.gpgsign", "false"]);
  for (const rel of UPDATER_RUNTIME_FILES) {
    const src = path.join(repoRoot, rel);
    const dst = path.join(workDir, rel);
    await fs.mkdir(path.dirname(dst), { recursive: true });
    await fs.copyFile(src, dst);
  }
  const manifestPath = path.join(workDir, "plugin.json");
  const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8")) as Record<string, unknown>;
  manifest.version = tagVersion;
  await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
  gitSync(workDir, ["add", "."]);
  gitSync(workDir, ["commit", "-m", `release v${tagVersion}`]);
  gitSync(workDir, ["tag", "-a", `v${tagVersion}`, "-m", `v${tagVersion}`]);
  gitSync(workDir, ["remote", "add", "origin", bareDir]);
  gitSync(workDir, ["push", "origin", "main", "--tags"]);
  return pathToFileURL(bareDir).href;
}

describe("installer --bin-shim", () => {
  let tmpRoot: string;
  let repoVersion: string;

  before(async () => {
    tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-bin-shim-"));
    helpers = (await import(pathToFileURL(INSTALL_SCRIPT).href)) as ShimHelpers;
    const manifest = JSON.parse(
      await fs.readFile(path.resolve(process.cwd(), "plugin.json"), "utf8"),
    ) as { version: string };
    repoVersion = manifest.version;
  });

  after(async () => {
    await fs.rm(tmpRoot, { recursive: true, force: true });
  });

  it("installs shims into ~/.local/bin when on PATH and executes agy-fast & agy-fast-mcp cleanly", async () => {
    const home = path.join(tmpRoot, "case-default-home");
    const localBin = path.join(home, ".local", "bin");
    const pluginDir = path.join(tmpRoot, "case-default-plugin");
    await fs.mkdir(localBin, { recursive: true });

    const env = makeIsolatedEnv(home, [localBin]);
    const out = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--bin-shim", "--no-enable"],
      { env, encoding: "utf8" },
    );

    assert.match(out, /Installed bin shim\(s\) in .*\.local[\\/]+bin: agy-fast(?:\.cmd)?, agy-fast-mcp(?:\.cmd)?/);
    assert.match(out, /Bin shims\s+: OK \(agy-fast(?:\.cmd)?, agy-fast-mcp(?:\.cmd)? in /);

    const cliShim = path.join(localBin, shimFileName("agy-fast"));
    const mcpShim = path.join(localBin, shimFileName("agy-fast-mcp"));

    if (IS_WIN) {
      const cliBody = await fs.readFile(cliShim, "utf8");
      const mcpBody = await fs.readFile(mcpShim, "utf8");
      assert.match(cliBody, /@rem agy-fast-bin-shim/);
      assert.match(cliBody, /@setlocal DisableDelayedExpansion/);
      assert.doesNotMatch(cliBody, /@?endlocal/i);
      assert.match(mcpBody, /@rem agy-fast-bin-shim/);
      assert.match(mcpBody, /@setlocal DisableDelayedExpansion/);
      assert.doesNotMatch(mcpBody, /@?endlocal/i);
      assert.equal(
        helpers.parseShimWrapper(cliBody).targetPath,
        path.join(pluginDir, "scripts", "install.mjs"),
      );
      assert.equal(
        helpers.parseShimWrapper(mcpBody).targetPath,
        path.join(pluginDir, "dist", "mcp-server.mjs"),
      );
    } else {
      const cliStat = await fs.lstat(cliShim);
      const mcpStat = await fs.lstat(mcpShim);
      assert.ok(cliStat.isSymbolicLink(), "agy-fast shim should be a symlink on POSIX");
      assert.ok(mcpStat.isSymbolicLink(), "agy-fast-mcp shim should be a symlink on POSIX");
      assert.equal(
        await fs.realpath(cliShim),
        await fs.realpath(path.join(pluginDir, "scripts", "install.mjs")),
      );
      assert.equal(
        await fs.realpath(mcpShim),
        await fs.realpath(path.join(pluginDir, "dist", "mcp-server.mjs")),
      );
      assert.notEqual((await fs.stat(cliShim)).mode & 0o111, 0);
      assert.notEqual((await fs.stat(mcpShim)).mode & 0o111, 0);
    }

    const helpRes = runShimCommand("agy-fast", ["--help"], env);
    assert.equal(helpRes.status, 0, helpRes.stderr);
    assert.match(helpRes.stdout, /agy-fast installer/);
    assert.match(helpRes.stdout, /--bin-shim/);

    const mcpHelpRes = runShimCommand("agy-fast-mcp", ["--cli", "--help"], env);
    assert.equal(mcpHelpRes.status, 0, mcpHelpRes.stderr);
    assert.match(mcpHelpRes.stdout, /agy-fast direct CLI mode/);

    const forwardedMcpHelp = runShimCommand("agy-fast", ["mcp", "--cli", "--help"], env);
    assert.equal(forwardedMcpHelp.status, 0, forwardedMcpHelp.stderr);
    assert.match(forwardedMcpHelp.stdout, /agy-fast direct CLI mode/);
  });

  it("includes ~/bin as a default user PATH bin directory alongside ~/.local/bin", async () => {
    const home = path.join(tmpRoot, "case-home-bin");
    const homeBin = path.join(home, "bin");
    const pluginDir = path.join(tmpRoot, "case-home-bin-plugin");
    await fs.mkdir(homeBin, { recursive: true });

    const env = makeIsolatedEnv(home, [homeBin]);
    const installOut = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--bin-shim", "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(installOut, /Installed bin shim\(s\) in .*[\\/]bin: agy-fast(?:\.cmd)?, agy-fast-mcp(?:\.cmd)?/);
    assert.match(installOut, /Bin shims\s+: OK /);

    const cliShim = path.join(homeBin, shimFileName("agy-fast"));
    assert.ok(await fs.lstat(cliShim));

    const helpRes = runShimCommand("agy-fast", ["--help"], env);
    assert.equal(helpRes.status, 0, helpRes.stderr);
    assert.match(helpRes.stdout, /agy-fast installer/);

    const docRes = runInstaller(["doctor", "--target", pluginDir], env);
    assert.equal(docRes.status, 0, docRes.stderr);
    assert.match(docRes.stdout, /Bin shims\s+: OK \(agy-fast(?:\.cmd)?, agy-fast-mcp(?:\.cmd)? in /);

    const rmOut = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "uninstall", "--target", pluginDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(rmOut, /Removed bin shim\(s\) from /);
    await assert.rejects(fs.lstat(cliShim));
  });

  it("supports --bin-shim-dir (creating directory, noting non-PATH, and idempotent re-run)", async () => {
    const home = path.join(tmpRoot, "case-custom-dir-home");
    const customBin = path.join(tmpRoot, "custom bin dir", "nested");
    const pluginDir1 = path.join(tmpRoot, "case-custom-plugin-1");
    const pluginDir2 = path.join(tmpRoot, "case custom plugin 2");
    await fs.mkdir(home, { recursive: true });

    const env = makeIsolatedEnv(home);
    const out1 = execFileSync(
      process.execPath,
      [
        INSTALL_SCRIPT,
        "install",
        "--target",
        pluginDir1,
        "--bin-shim-dir",
        customBin,
        "--no-enable",
      ],
      { env, encoding: "utf8" },
    );
    assert.match(out1, /Installed bin shim\(s\) in /);
    assert.match(out1, /is not currently on PATH/);
    assert.match(out1, /Bin shims\s+: OK /);

    // Idempotent re-run against the same plugin target
    const out2 = execFileSync(
      process.execPath,
      [
        INSTALL_SCRIPT,
        "install",
        "--target",
        pluginDir1,
        `--bin-shim-dir=${customBin}`,
        "--no-enable",
      ],
      { env, encoding: "utf8" },
    );
    assert.match(out2, /Bin shims\s+: OK /);

    // Re-pointing owned shims to a new plugin installation succeeds
    execFileSync(
      process.execPath,
      [
        INSTALL_SCRIPT,
        "install",
        "--target",
        pluginDir2,
        "--bin-shim-dir",
        customBin,
        "--no-enable",
      ],
      { env, encoding: "utf8" },
    );
    const cliShim = path.join(customBin, shimFileName("agy-fast"));
    const mcpShim = path.join(customBin, shimFileName("agy-fast-mcp"));
    if (!IS_WIN) {
      assert.equal(
        await fs.realpath(cliShim),
        await fs.realpath(path.join(pluginDir2, "scripts", "install.mjs")),
      );
    } else {
      const body = await fs.readFile(cliShim, "utf8");
      assert.equal(
        helpers.parseShimWrapper(body).targetPath,
        path.join(pluginDir2, "scripts", "install.mjs"),
      );
    }

    const res = runShimCommand(cliShim, ["--help"], env);
    assert.equal(res.status, 0, res.stderr);
    assert.match(res.stdout, /agy-fast installer/);

    const mcpRes = runShimCommand(mcpShim, ["--cli", "--help"], env);
    assert.equal(mcpRes.status, 0, mcpRes.stderr);
    assert.match(mcpRes.stdout, /agy-fast direct CLI mode/);
  });

  it("prints a non-fatal actionable hint without modifying shell rc files when no user PATH bin dir exists", async () => {
    const homeMissing = path.join(tmpRoot, "case-no-local-bin");
    const homeNotOnPath = path.join(tmpRoot, "case-not-on-path");
    const pluginDir = path.join(tmpRoot, "case-no-path-plugin");
    await fs.mkdir(homeMissing, { recursive: true });
    await fs.mkdir(path.join(homeNotOnPath, ".local", "bin"), { recursive: true });

    const outMissing = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--bin-shim", "--no-enable"],
      { env: makeIsolatedEnv(homeMissing), encoding: "utf8" },
    );
    assert.match(outMissing, /skipped --bin-shim/i);
    assert.match(outMissing, /--bin-shim-dir/);
    assert.match(outMissing, /Installation complete/);

    const outNotOnPath = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--bin-shim", "--no-enable"],
      { env: makeIsolatedEnv(homeNotOnPath), encoding: "utf8" },
    );
    assert.match(outNotOnPath, /is not on PATH/);
    assert.match(outNotOnPath, /--bin-shim-dir/);
    assert.match(outNotOnPath, /Installation complete/);

    for (const h of [homeMissing, homeNotOnPath]) {
      for (const rc of SHELL_RC_FILES) {
        await assert.rejects(fs.lstat(path.join(h, rc)), `Must never create ${rc}`);
      }
    }

    // Expands ~/ entries in PATH (including trailing separator) cleanly
    const tildeEnv = makeIsolatedEnv(homeNotOnPath, ["~/.local/bin/"]);
    const outTilde = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--bin-shim", "--no-enable"],
      { env: tildeEnv, encoding: "utf8" },
    );
    assert.match(outTilde, /Installed bin shim\(s\) in /);
    assert.match(outTilde, /Bin shims\s+: OK /);
  });

  it("supports --link dev mode and skips global --bin-shim on --project unless --bin-shim-dir is given", async () => {
    const home = path.join(tmpRoot, "case-link-proj-home");
    const localBin = path.join(home, ".local", "bin");
    const linkTarget = path.join(tmpRoot, "case-linked-plugin");
    const projDir = path.join(tmpRoot, "case-project-repo");
    const projBin = path.join(tmpRoot, "case-project-bin");
    await fs.mkdir(localBin, { recursive: true });
    await fs.mkdir(projDir, { recursive: true });

    const env = makeIsolatedEnv(home, [localBin]);

    // 1. --project with --bin-shim (no --bin-shim-dir) skips installing into ~/.local/bin
    const projSkipOut = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--project", projDir, "--bin-shim", "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(projSkipOut, /skipped --bin-shim for --project/i);
    await assert.rejects(fs.lstat(path.join(localBin, shimFileName("agy-fast"))));

    // 2. --project with explicit --bin-shim-dir installs shims into custom dir
    const projExplicitOut = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--project", projDir, "--bin-shim-dir", projBin, "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(projExplicitOut, /Installed bin shim\(s\) in /);

    // 3. --link mode works with --bin-shim and cleans up cleanly on uninstall
    const linkOut = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", linkTarget, "--link", "--bin-shim", "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(linkOut, /Linked /);
    assert.match(linkOut, /Installed bin shim\(s\) in /);

    const helpRes = runShimCommand("agy-fast", ["--help"], env);
    assert.equal(helpRes.status, 0, helpRes.stderr);

    const rmOut = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "uninstall", "--target", linkTarget, "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(rmOut, /Removed bin shim\(s\) from /);
    await assert.rejects(fs.lstat(path.join(localBin, shimFileName("agy-fast"))));
    await assert.rejects(fs.lstat(path.join(localBin, shimFileName("agy-fast-mcp"))));
  });

  it("protects pre-existing unrelated files, symlinks, and global npm/pnpm node_modules symlinks from overwriting", async () => {
    // Unit-level segment matching checks (POSIX & Windows)
    assert.equal(helpers.isInsideNodeModules("/usr/local/lib/node_modules/agy-fast"), true);
    assert.equal(
      helpers.isInsideNodeModules("/home/u/.local/share/pnpm/global/5/.pnpm/[email protected]/node_modules/agy-fast"),
      true,
    );
    assert.equal(
      helpers.isInsideNodeModules("C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\agy-fast"),
      true,
    );
    assert.equal(helpers.isInsideNodeModules("/home/u/.gemini/config/plugins/agy-fast"), false);
    assert.equal(helpers.isInsideNodeModules("/home/u/my_node_modules/agy-fast"), false);
    assert.equal(helpers.isInsideNodeModules("/home/u/node_modules/../agy-fast"), false);

    const home = path.join(tmpRoot, "case-collision-home");
    const binDir = path.join(tmpRoot, "case-collision-bin");
    const pluginDir = path.join(tmpRoot, "case-collision-plugin");
    const unrelatedDir = path.join(tmpRoot, "unrelated-tool");
    await fs.mkdir(home, { recursive: true });
    await fs.mkdir(binDir, { recursive: true });
    await fs.mkdir(path.join(unrelatedDir, "scripts"), { recursive: true });

    const foreignCli = path.join(binDir, shimFileName("agy-fast"));
    const originalContent = IS_WIN ? "@echo FOREIGN_CLI\r\n" : "#!/bin/sh\necho FOREIGN_CLI\n";
    await fs.writeFile(foreignCli, originalContent, "utf8");
    if (!IS_WIN) {
      await fs.chmod(foreignCli, 0o755);
    }

    const foreignMcp = path.join(binDir, shimFileName("agy-fast-mcp"));
    const unrelatedScript = path.join(unrelatedDir, "scripts", "install.mjs");
    await fs.writeFile(unrelatedScript, "// unrelated tool\n", "utf8");
    if (!IS_WIN) {
      await fs.symlink(unrelatedScript, foreignMcp);
    } else {
      await fs.writeFile(foreignMcp, "@echo FOREIGN_MCP\r\n", "utf8");
    }

    const env = makeIsolatedEnv(home, [binDir]);
    const res = runInstaller(
      ["install", "--target", pluginDir, "--bin-shim-dir", binDir, "--no-enable"],
      env,
    );
    assert.equal(res.status, 0, res.stderr);
    assert.match(res.stderr, /Warning: skipped bin shim .*agy-fast/);
    assert.match(res.stderr, /Warning: skipped bin shim .*agy-fast-mcp/);
    assert.equal(await fs.readFile(foreignCli, "utf8"), originalContent);
    if (!IS_WIN) {
      assert.equal(await fs.readlink(foreignMcp), unrelatedScript);
    }

    // Partial collision: remove foreign agy-fast-mcp and verify it gets installed while foreign agy-fast stays untouched
    await fs.unlink(foreignMcp);
    const partialRes = runInstaller(
      ["install", "--target", pluginDir, "--bin-shim-dir", binDir, "--no-enable"],
      env,
    );
    assert.equal(partialRes.status, 0, partialRes.stderr);
    assert.match(partialRes.stderr, /Warning: skipped bin shim .*agy-fast/);
    assert.match(partialRes.stdout, /Installed bin shim\(s\) in .*agy-fast-mcp/);
    assert.equal(await fs.readFile(foreignCli, "utf8"), originalContent);
    assert.ok(await fs.lstat(foreignMcp));

    // P1 #1 POSIX regression: existing global npm/pnpm node_modules/agy-fast symlink must be
    // classified as foreign and NEVER overwritten by install or deleted by uninstall.
    if (!IS_WIN) {
      const npmPrefix = path.join(tmpRoot, "case-npm-global-prefix");
      const npmBin = path.join(npmPrefix, "bin");
      const npmPkgRoot = path.join(npmPrefix, "lib", "node_modules", "agy-fast");
      await fs.mkdir(npmBin, { recursive: true });
      await fs.mkdir(path.join(npmPkgRoot, "scripts"), { recursive: true });
      await fs.mkdir(path.join(npmPkgRoot, "dist"), { recursive: true });
      await fs.writeFile(
        path.join(npmPkgRoot, "plugin.json"),
        JSON.stringify({ name: "agy-fast", version: repoVersion }),
        "utf8",
      );
      await fs.writeFile(
        path.join(npmPkgRoot, "package.json"),
        JSON.stringify({ name: "agy-fast", version: repoVersion }),
        "utf8",
      );
      const npmCliTarget = path.join(npmPkgRoot, "scripts", "install.mjs");
      const npmMcpTarget = path.join(npmPkgRoot, "dist", "mcp-server.mjs");
      await fs.writeFile(npmCliTarget, "#!/usr/bin/env node\n// npm global cli\n", "utf8");
      await fs.writeFile(npmMcpTarget, "#!/usr/bin/env node\n// npm global mcp\n", "utf8");
      await fs.chmod(npmCliTarget, 0o755);
      await fs.chmod(npmMcpTarget, 0o755);

      const npmCliLink = path.join(npmBin, "agy-fast");
      const npmMcpLink = path.join(npmBin, "agy-fast-mcp");
      await fs.symlink("../lib/node_modules/agy-fast/scripts/install.mjs", npmCliLink);
      await fs.symlink("../lib/node_modules/agy-fast/dist/mcp-server.mjs", npmMcpLink);

      const inspectedCli = await helpers.inspectBinShim(npmBin, {
        name: "agy-fast",
        relTarget: path.join("scripts", "install.mjs"),
      });
      assert.equal(inspectedCli.status, "foreign");
      assert.equal(inspectedCli.owned, false);

      const npmInstallRes = runInstaller(
        ["install", "--target", pluginDir, "--bin-shim-dir", npmBin, "--no-enable"],
        makeIsolatedEnv(home, [npmBin]),
      );
      assert.equal(npmInstallRes.status, 0, npmInstallRes.stderr);
      assert.match(npmInstallRes.stderr, /Warning: skipped bin shim .*agy-fast/);
      assert.match(npmInstallRes.stderr, /Warning: skipped bin shim .*agy-fast-mcp/);
      assert.equal(
        await fs.readlink(npmCliLink),
        "../lib/node_modules/agy-fast/scripts/install.mjs",
      );
      assert.equal(
        await fs.readlink(npmMcpLink),
        "../lib/node_modules/agy-fast/dist/mcp-server.mjs",
      );

      // doctor passes and notes non-agy-fast present
      const npmDocRes = runInstaller(
        ["doctor", "--target", pluginDir, "--bin-shim-dir", npmBin],
        makeIsolatedEnv(home, [npmBin]),
      );
      assert.equal(npmDocRes.status, 0, npmDocRes.stderr);
      assert.match(npmDocRes.stdout, /Bin shims\s+: none in .*non-agy-fast present: agy-fast, agy-fast-mcp/);

      // uninstall against npmPkgRoot must NOT delete node_modules-managed symlinks
      const npmUninstRes = runInstaller(
        ["uninstall", "--target", pluginDir, "--bin-shim-dir", npmBin, "--no-enable"],
        makeIsolatedEnv(home, [npmBin]),
      );
      assert.equal(npmUninstRes.status, 0, npmUninstRes.stderr);
      assert.equal(
        await fs.readlink(npmCliLink),
        "../lib/node_modules/agy-fast/scripts/install.mjs",
      );
    }
  });

  it("never follows symlinks in writeFileAtomically fallback when rename fails (P1 #2)", async () => {
    const dir = path.join(tmpRoot, "case-atomic-symlink");
    await fs.mkdir(dir, { recursive: true });

    const sentinelContent = "// ORIGINAL PLUGIN SCRIPT — MUST NEVER BE CLOBBERED\n";
    const targetScript = path.join(dir, "install.mjs");
    await fs.writeFile(targetScript, sentinelContent, "utf8");

    if (!IS_WIN) {
      // Case A: rename fails once (EPERM) while destination is a symlink, then succeeds after unlink
      const linkOnce = path.join(dir, "shim-retry-ok");
      await fs.symlink(targetScript, linkOnce);
      let renameCalls = 0;
      const failOnceOps: typeof fs = {
        ...fs,
        rename: async (oldPath, newPath) => {
          renameCalls++;
          if (renameCalls === 1) {
            const err = new Error("Simulated EPERM on rename") as NodeJS.ErrnoException;
            err.code = "EPERM";
            throw err;
          }
          return fs.rename(oldPath, newPath);
        },
      };
      await helpers.writeFileAtomically(linkOnce, "#!/bin/sh\necho WRAPPER_A\n", 0o755, failOnceOps);
      assert.equal(await fs.readFile(targetScript, "utf8"), sentinelContent);
      const statA = await fs.lstat(linkOnce);
      assert.equal(statA.isSymbolicLink(), false);
      assert.equal(statA.isFile(), true);
      assert.equal(await fs.readFile(linkOnce, "utf8"), "#!/bin/sh\necho WRAPPER_A\n");
      assert.notEqual(statA.mode & 0o111, 0);

      // Case B: rename ALWAYS fails (EPERM) while destination is a symlink — uses exclusive creation, never follows symlink
      const linkAlways = path.join(dir, "shim-always-fail-rename");
      await fs.symlink(targetScript, linkAlways);
      const alwaysFailRenameOps: typeof fs = {
        ...fs,
        rename: async () => {
          const err = new Error("Simulated persistent EPERM on rename") as NodeJS.ErrnoException;
          err.code = "EPERM";
          throw err;
        },
      };
      await helpers.writeFileAtomically(
        linkAlways,
        "#!/bin/sh\necho WRAPPER_B\n",
        0o755,
        alwaysFailRenameOps,
      );
      assert.equal(await fs.readFile(targetScript, "utf8"), sentinelContent);
      const statB = await fs.lstat(linkAlways);
      assert.equal(statB.isSymbolicLink(), false);
      assert.equal(statB.isFile(), true);
      assert.equal(await fs.readFile(linkAlways, "utf8"), "#!/bin/sh\necho WRAPPER_B\n");
      assert.notEqual(statB.mode & 0o111, 0);

      // Case C: unlink fails (EACCES) — rethrows and leaves symlink target untouched
      const linkFailUnlink = path.join(dir, "shim-fail-unlink");
      await fs.symlink(targetScript, linkFailUnlink);
      const failUnlinkOps: typeof fs = {
        ...alwaysFailRenameOps,
        unlink: async () => {
          const err = new Error("Simulated EACCES on unlink") as NodeJS.ErrnoException;
          err.code = "EACCES";
          throw err;
        },
      };
      await assert.rejects(
        helpers.writeFileAtomically(linkFailUnlink, "#!/bin/sh\necho WRAPPER_C\n", 0o755, failUnlinkOps),
        (err: NodeJS.ErrnoException) => err.code === "EACCES",
      );
      assert.equal(await fs.readFile(targetScript, "utf8"), sentinelContent);
      assert.equal((await fs.lstat(linkFailUnlink)).isSymbolicLink(), true);

      // Case D: on POSIX, rename failure against a regular file rethrows instead of falling back to copyFile
      const regFile = path.join(dir, "regular-file");
      await fs.writeFile(regFile, "ORIGINAL_REG\n", "utf8");
      await assert.rejects(
        helpers.writeFileAtomically(regFile, "NEW_REG\n", 0o755, alwaysFailRenameOps),
        (err: NodeJS.ErrnoException) => err.code === "EPERM",
      );
      assert.equal(await fs.readFile(regFile, "utf8"), "ORIGINAL_REG\n");
    } else {
      // On Windows, verify locked regular file fallback works when rename throws EBUSY
      const regFile = path.join(dir, "locked-shim.cmd");
      await fs.writeFile(regFile, "@rem old\r\n", "utf8");
      const busyRenameOps: typeof fs = {
        ...fs,
        rename: async () => {
          const err = new Error("Simulated EBUSY") as NodeJS.ErrnoException;
          err.code = "EBUSY";
          throw err;
        },
      };
      await helpers.writeFileAtomically(regFile, "@rem new\r\n", null, busyRenameOps);
      assert.equal(await fs.readFile(regFile, "utf8"), "@rem new\r\n");
    }
  });

  it("creates and repairs bin shims on update --bin-shim even when already up-to-date (P1 #3) and avoids unnecessary chmod (P2)", async () => {
    const home = path.join(tmpRoot, "case-update-uptodate-home");
    const localBin = path.join(home, ".local", "bin");
    const pluginDir = path.join(tmpRoot, "case-update-uptodate-plugin");
    const cacheDir = path.join(tmpRoot, "case-update-uptodate-cache");
    const repoFixtureRoot = path.join(tmpRoot, "case-update-uptodate-repo");
    await fs.mkdir(localBin, { recursive: true });
    await fs.mkdir(repoFixtureRoot, { recursive: true });

    const bareRepoUrl = await createLocalTagRepo(repoFixtureRoot, repoVersion);
    const env = makeIsolatedEnv(home, [localBin], {
      AGY_FAST_CACHE_DIR: cacheDir,
      AGY_FAST_REPO: bareRepoUrl,
    });

    // Install plugin WITHOUT --bin-shim
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    const cliShim = path.join(localBin, shimFileName("agy-fast"));
    const mcpShim = path.join(localBin, shimFileName("agy-fast-mcp"));
    await assert.rejects(fs.lstat(cliShim));

    // update --check --bin-shim must NOT create shims
    const checkRes = runInstaller(
      ["update", "--check", "--target", pluginDir, "--bin-shim"],
      env,
    );
    assert.equal(checkRes.status, 0, checkRes.stderr);
    assert.match(checkRes.stdout, /already up to date/i);
    await assert.rejects(fs.lstat(cliShim));

    // P2: on POSIX, if target scripts are already executable (0o555), update --bin-shim
    // must NOT unnecessarily chmod them to 0o755 (read-only mount safety).
    const installedCliScript = path.join(pluginDir, "scripts", "install.mjs");
    const installedMcpScript = path.join(pluginDir, "dist", "mcp-server.mjs");
    if (!IS_WIN) {
      await fs.chmod(installedCliScript, 0o555);
      await fs.chmod(installedMcpScript, 0o555);
    }

    // update --bin-shim on already up-to-date installation MUST create the shims
    const upCreateRes = runInstaller(
      ["update", "--target", pluginDir, "--bin-shim"],
      env,
    );
    assert.equal(upCreateRes.status, 0, upCreateRes.stderr);
    assert.match(upCreateRes.stdout, /already up to date/i);
    assert.match(upCreateRes.stdout, /Installed bin shim\(s\) in /);
    assert.ok(await fs.lstat(cliShim));
    assert.ok(await fs.lstat(mcpShim));
    if (!IS_WIN) {
      assert.equal((await fs.stat(installedCliScript)).mode & 0o777, 0o555);
      assert.equal((await fs.stat(installedMcpScript)).mode & 0o777, 0o555);
      // Restore writable permissions for repair test and cleanup
      await fs.chmod(installedCliScript, 0o644);
      await fs.chmod(installedMcpScript, 0o755);
    }

    // Break agy-fast shim (dangling target) and verify update --bin-shim-dir repairs it when up-to-date
    await fs.unlink(cliShim);
    const deletedPlugin = path.join(tmpRoot, "case-update-deleted-plugin");
    if (IS_WIN) {
      await fs.writeFile(
        cliShim,
        helpers.renderWindowsCmdShim(path.join(deletedPlugin, "scripts", "install.mjs")),
        "utf8",
      );
    } else {
      await fs.symlink(path.join(deletedPlugin, "scripts", "install.mjs"), cliShim);
    }
    const brokenDoc = runInstaller(["doctor", "--target", pluginDir], env);
    assert.notEqual(brokenDoc.status, 0);
    assert.match(brokenDoc.stdout, /Bin shims\s+: BROKEN/);

    const upRepairRes = runInstaller(
      ["update", "--target", pluginDir, "--bin-shim-dir", localBin],
      env,
    );
    assert.equal(upRepairRes.status, 0, upRepairRes.stderr);
    assert.match(upRepairRes.stdout, /already up to date/i);
    assert.match(upRepairRes.stdout, /Installed bin shim\(s\) in /);

    if (!IS_WIN) {
      // Target script that had 0o644 (non-exec) WAS repaired to executable
      assert.notEqual((await fs.stat(installedCliScript)).mode & 0o111, 0);
    }

    const fixedDoc = runInstaller(["doctor", "--target", pluginDir], env);
    assert.equal(fixedDoc.status, 0, fixedDoc.stderr);
    assert.match(fixedDoc.stdout, /Bin shims\s+: OK /);
  });

  it("emits DisableDelayedExpansion and ASCII-only non-ASCII Windows .cmd trampolines with faithful argv forwarding (P1 #4)", async () => {
    // 1. ASCII path containing spaces, '!', and '%'
    const asciiBangPath = "C:\\Users\\dev!1\\100% dir\\agy-fast\\scripts\\install.mjs";
    const asciiCmd = helpers.renderWindowsCmdShim(asciiBangPath);
    const asciiLines = asciiCmd.split("\r\n").filter(Boolean);
    assert.equal(asciiLines[0], "@rem agy-fast-bin-shim");
    assert.equal(asciiLines[1], "@setlocal DisableDelayedExpansion");
    assert.equal(
      asciiLines[2],
      '@node "C:\\Users\\dev!1\\100%% dir\\agy-fast\\scripts\\install.mjs" %*',
    );
    assert.equal(asciiLines.length, 3, "Final line must be @node without trailing @endlocal");
    assert.doesNotMatch(asciiCmd, /@?endlocal/i);
    assert.deepEqual(helpers.parseShimWrapper(asciiCmd), {
      hasMarker: true,
      targetPath: asciiBangPath,
    });

    // 2. Non-ASCII / CJK / emoji / '!' / '%' / "'" / '&' path
    const cjkPath = "C:\\Users\\张三!100% O'Brien & 🚀\\agy-fast\\scripts\\install.mjs";
    const cjkCmd = helpers.renderWindowsCmdShim(cjkPath);
    assert.match(cjkCmd, /^[\x20-\x7e\r\n]+$/, "Non-ASCII Windows .cmd shim must be strictly ASCII-only");
    const cjkLines = cjkCmd.split("\r\n").filter(Boolean);
    assert.equal(cjkLines[0], "@rem agy-fast-bin-shim");
    assert.match(cjkLines[1]!, /^@rem agy-fast-target: "/);
    assert.ok(!cjkLines[1]!.includes("%") && !cjkLines[1]!.includes("!"));
    assert.equal(cjkLines[2], "@setlocal DisableDelayedExpansion");
    assert.match(cjkLines[3]!, /^@node -e "[^"%!]+" -- %\*$/);
    assert.equal(cjkLines.length, 4, "Final line must be @node -e without trailing @endlocal");
    assert.doesNotMatch(cjkCmd, /@?endlocal/i);

    // Round-trip via metadata comment AND via fallback when metadata comment is removed
    assert.deepEqual(helpers.parseShimWrapper(cjkCmd), {
      hasMarker: true,
      targetPath: cjkPath,
    });
    const withoutMeta = [cjkLines[0], cjkLines[2], cjkLines[3], ""].join("\r\n");
    assert.deepEqual(helpers.parseShimWrapper(withoutMeta), {
      hasMarker: true,
      targetPath: cjkPath,
    });

    // Rejects unsafe characters
    for (const bad of ["C:\\bad\"path\\install.mjs", "C:\\bad\npath", "C:\\bad\rpath", "C:\\bad\0path"]) {
      assert.throws(() => helpers.renderWindowsCmdShim(bad), /Unsafe character/);
    }

    // 3. Execute the rendered non-ASCII node -e trampoline logic in real Node across all OSes
    const unicodePluginDir = path.join(tmpRoot, "用户!100% O'Brien", "agy-fast");
    const unicodeHome = path.join(tmpRoot, "case-unicode-home");
    await fs.mkdir(unicodeHome, { recursive: true });
    const unicodeEnv = makeIsolatedEnv(unicodeHome);
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", unicodePluginDir, "--no-enable"],
      { env: unicodeEnv, encoding: "utf8" },
    );

    const extractTrampolineCode = (cmdContent: string): string => {
      const m = /^@node -e "([^"]+)" -- %\*$/m.exec(cmdContent);
      assert.ok(m && m[1], `Expected @node -e trampoline in:\n${cmdContent}`);
      return m[1];
    };

    const unicodeCliTarget = path.join(unicodePluginDir, "scripts", "install.mjs");
    const unicodeMcpTarget = path.join(unicodePluginDir, "dist", "mcp-server.mjs");
    const cliTrampoline = extractTrampolineCode(helpers.renderWindowsCmdShim(unicodeCliTarget));
    const mcpTrampoline = extractTrampolineCode(helpers.renderWindowsCmdShim(unicodeMcpTarget));

    const cliHelp = spawnSync(process.execPath, ["-e", cliTrampoline, "--", "--help"], {
      env: unicodeEnv,
      encoding: "utf8",
    });
    assert.equal(cliHelp.status, 0, cliHelp.stderr);
    assert.match(cliHelp.stdout, /agy-fast installer/);

    const cliMcpForward = spawnSync(
      process.execPath,
      ["-e", cliTrampoline, "--", "mcp", "--cli", "--help"],
      { env: unicodeEnv, encoding: "utf8" },
    );
    assert.equal(cliMcpForward.status, 0, cliMcpForward.stderr);
    assert.match(cliMcpForward.stdout, /agy-fast direct CLI mode/);

    const cliBadFlag = spawnSync(
      process.execPath,
      ["-e", cliTrampoline, "--", "--no-such-flag-xyz"],
      { env: unicodeEnv, encoding: "utf8" },
    );
    assert.notEqual(cliBadFlag.status, 0);
    assert.match(cliBadFlag.stderr, /Unknown option/);

    const mcpHelp = spawnSync(process.execPath, ["-e", mcpTrampoline, "--", "--cli", "--help"], {
      env: unicodeEnv,
      encoding: "utf8",
    });
    assert.equal(mcpHelp.status, 0, mcpHelp.stderr);
    assert.match(mcpHelp.stdout, /agy-fast direct CLI mode/);

    const mcpBadFlag = spawnSync(
      process.execPath,
      ["-e", mcpTrampoline, "--", "--no-such-flag-xyz"],
      { env: unicodeEnv, encoding: "utf8" },
    );
    assert.notEqual(mcpBadFlag.status, 0);

    // Custom fixture verifying exact process.argv[1] and forwarded flags (including --, -v, !, CJK)
    const echoScript = path.join(unicodePluginDir, "echo-argv.mjs");
    await fs.writeFile(
      echoScript,
      "process.stdout.write(JSON.stringify(process.argv.slice(1)));\n",
      "utf8",
    );
    const echoTrampoline = extractTrampolineCode(helpers.renderWindowsCmdShim(echoScript));
    const echoArgs = ["--help", "-v", "--", "a!b", "你好"];
    const echoRes = spawnSync(process.execPath, ["-e", echoTrampoline, "--", ...echoArgs], {
      env: unicodeEnv,
      encoding: "utf8",
    });
    assert.equal(echoRes.status, 0, echoRes.stderr);
    assert.deepEqual(JSON.parse(echoRes.stdout), [echoScript, ...echoArgs]);

    // Missing target exits non-zero cleanly
    const missingTrampoline = extractTrampolineCode(
      helpers.renderWindowsCmdShim(path.join(unicodePluginDir, "missing-script.mjs")),
    );
    const missingRes = spawnSync(process.execPath, ["-e", missingTrampoline, "--"], {
      env: unicodeEnv,
      encoding: "utf8",
    });
    assert.notEqual(missingRes.status, 0);

    // 4. On real Windows, also execute actual .cmd shims under cmd.exe /v:on (DelayedExpansion enabled!)
    if (IS_WIN) {
      const bangPlugin = path.join(tmpRoot, "win!bang!plugin");
      const bangBin = path.join(tmpRoot, "win-bang-bin");
      execFileSync(
        process.execPath,
        [INSTALL_SCRIPT, "install", "--target", bangPlugin, "--bin-shim-dir", bangBin, "--no-enable"],
        { env: unicodeEnv, encoding: "utf8" },
      );
      const bangRes = runShimCommand(
        path.join(bangBin, "agy-fast.cmd"),
        ["--help"],
        unicodeEnv,
        ["/v:on"],
      );
      assert.equal(bangRes.status, 0, bangRes.stderr);
      assert.match(bangRes.stdout, /agy-fast installer/);

      const cjkBin = path.join(tmpRoot, "win-cjk-bin");
      execFileSync(
        process.execPath,
        [
          INSTALL_SCRIPT,
          "install",
          "--target",
          unicodePluginDir,
          "--bin-shim-dir",
          cjkBin,
          "--no-enable",
        ],
        { env: unicodeEnv, encoding: "utf8" },
      );
      const cjkRes = runShimCommand(
        path.join(cjkBin, "agy-fast.cmd"),
        ["--help"],
        unicodeEnv,
        ["/v:on"],
      );
      assert.equal(cjkRes.status, 0, cjkRes.stderr);
      assert.match(cjkRes.stdout, /agy-fast installer/);
    }
  });

  it("reports status/doctor cleanly when absent, present, wrapper-backed, or broken, and skips unrelated global shims for --project (P2)", async () => {
    const home = path.join(tmpRoot, "case-doctor-home");
    const localBin = path.join(home, ".local", "bin");
    const pluginDir = path.join(tmpRoot, "case-doctor-plugin");
    const wrapperBin = path.join(tmpRoot, "case-doctor-wrapper-bin");
    const projDir = path.join(tmpRoot, "case-doctor-project");
    const projBrokenBin = path.join(tmpRoot, "case-doctor-project-broken-bin");
    const repoFixtureRoot = path.join(tmpRoot, "case-doctor-proj-repo");
    await fs.mkdir(localBin, { recursive: true });
    await fs.mkdir(wrapperBin, { recursive: true });
    await fs.mkdir(projDir, { recursive: true });
    await fs.mkdir(projBrokenBin, { recursive: true });
    await fs.mkdir(repoFixtureRoot, { recursive: true });

    const bareRepoUrl = await createLocalTagRepo(repoFixtureRoot, repoVersion);
    const env = makeIsolatedEnv(home, [localBin], {
      AGY_FAST_CACHE_DIR: path.join(tmpRoot, "case-doctor-cache"),
      AGY_FAST_REPO: bareRepoUrl,
    });

    // Absent shims must never fail doctor
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    const cleanDoc = runInstaller(["doctor", "--target", pluginDir], env);
    assert.equal(cleanDoc.status, 0, cleanDoc.stderr);
    assert.doesNotMatch(cleanDoc.stdout, /Bin shims\s+:/);

    // Explicit --bin-shim-dir with no shims reports none and passes
    const emptyDirDoc = runInstaller(
      ["doctor", "--target", pluginDir, "--bin-shim-dir", wrapperBin],
      env,
    );
    assert.equal(emptyDirDoc.status, 0, emptyDirDoc.stderr);
    assert.match(emptyDirDoc.stdout, /Bin shims\s+: none in /);

    // Installed shims report OK
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginDir, "--bin-shim", "--no-enable"],
      { env, encoding: "utf8" },
    );
    const okDoc = runInstaller(["status", "--target", pluginDir], env);
    assert.equal(okDoc.status, 0, okDoc.stderr);
    assert.match(okDoc.stdout, /Bin shims\s+: OK \(agy-fast(?:\.cmd)?, agy-fast-mcp(?:\.cmd)? in /);

    // POSIX fallback wrapper with marker (and single-quote escaping) is recognized and executable
    if (!IS_WIN) {
      const wrapperCli = path.join(wrapperBin, "agy-fast");
      const targetCli = path.join(pluginDir, "scripts", "install.mjs");
      const escapedTargetCli = targetCli.replace(/'/g, "'\\''");
      await fs.writeFile(
        wrapperCli,
        `#!/usr/bin/env sh\n# agy-fast-bin-shim\n# agy-fast-target: ${JSON.stringify(targetCli)}\nexec node '${escapedTargetCli}' "$@"\n`,
        "utf8",
      );
      await fs.chmod(wrapperCli, 0o755);
      const wrapDoc = runInstaller(
        ["doctor", "--target", pluginDir, "--bin-shim-dir", wrapperBin],
        env,
      );
      assert.equal(wrapDoc.status, 0, wrapDoc.stderr);
      assert.match(wrapDoc.stdout, /Bin shims\s+: OK \(agy-fast in /);

      // Verify renderPosixShimWrapper + parseShimWrapper handle paths containing single quotes
      const quotePath = path.join(tmpRoot, "o'brien-plugin", "scripts", "install.mjs");
      const renderedPosix = helpers.renderPosixShimWrapper(quotePath);
      assert.deepEqual(helpers.parseShimWrapper(renderedPosix), {
        hasMarker: true,
        targetPath: quotePath,
      });
    }

    // Broken / dangling global agy-fast shim reports BROKEN and fails global doctor
    const brokenShim = path.join(localBin, shimFileName("agy-fast"));
    await fs.unlink(brokenShim);
    const deletedPlugin = path.join(tmpRoot, "deleted-old-plugin");
    if (IS_WIN) {
      await fs.writeFile(
        brokenShim,
        helpers.renderWindowsCmdShim(path.join(deletedPlugin, "scripts", "install.mjs")),
        "utf8",
      );
    } else {
      await fs.symlink(path.join(deletedPlugin, "scripts", "install.mjs"), brokenShim);
    }

    const brokenDoc = runInstaller(["doctor", "--target", pluginDir], env);
    assert.notEqual(brokenDoc.status, 0);
    assert.match(brokenDoc.stdout, /Bin shims\s+: BROKEN \(agy-fast(?:\.cmd)? in /);

    // P2 regression: doctor --project, status --project, and update --project (both up-to-date
    // and full updated post-update health check) must NOT fail on unrelated broken global shims
    // when --bin-shim-dir is omitted.
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--project", projDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    const projDoc = runInstaller(["doctor", "--project", projDir], env);
    assert.equal(projDoc.status, 0, projDoc.stderr);
    assert.doesNotMatch(projDoc.stdout, /Bin shims\s+: BROKEN/);

    const projStatus = runInstaller(["status", "--project", projDir], env);
    assert.equal(projStatus.status, 0, projStatus.stderr);

    const projUpdateUpToDate = runInstaller(["update", "--project", projDir], env);
    assert.equal(projUpdateUpToDate.status, 0, projUpdateUpToDate.stderr);

    // Trigger an actual update (parsed.status === "updated") so runUpdate executes runDoctor
    const projManifestPath = path.join(projDir, ".agents", "plugins", "agy-fast", "plugin.json");
    const projManifest = JSON.parse(await fs.readFile(projManifestPath, "utf8")) as Record<
      string,
      unknown
    >;
    projManifest.version = "0.0.1";
    await fs.writeFile(projManifestPath, `${JSON.stringify(projManifest, null, 2)}\n`, "utf8");
    const projUpdateApplied = runInstaller(["update", "--project", projDir], env);
    assert.equal(projUpdateApplied.status, 0, projUpdateApplied.stderr);
    assert.match(projUpdateApplied.stdout, /Updated agy-fast v0\.0\.1 ->/);
    assert.doesNotMatch(projUpdateApplied.stdout, /Bin shims\s+: BROKEN/);

    // Explicit --bin-shim-dir on doctor --project STILL checks that directory and reports BROKEN
    const brokenProjShim = path.join(projBrokenBin, shimFileName("agy-fast"));
    if (IS_WIN) {
      await fs.writeFile(
        brokenProjShim,
        helpers.renderWindowsCmdShim(path.join(deletedPlugin, "scripts", "install.mjs")),
        "utf8",
      );
    } else {
      await fs.symlink(path.join(deletedPlugin, "scripts", "install.mjs"), brokenProjShim);
    }
    const projExplicitBrokenDoc = runInstaller(
      ["doctor", "--project", projDir, "--bin-shim-dir", projBrokenBin],
      env,
    );
    assert.notEqual(projExplicitBrokenDoc.status, 0);
    assert.match(projExplicitBrokenDoc.stdout, /Bin shims\s+: BROKEN/);
  });

  it("uninstalls only shims pointing to the uninstalled targetDir and leaves others untouched", async () => {
    const home = path.join(tmpRoot, "case-uninstall-home");
    const binDir = path.join(tmpRoot, "case-uninstall-bin");
    const pluginA = path.join(tmpRoot, "case-uninstall-plugin-a");
    const pluginB = path.join(tmpRoot, "case-uninstall-plugin-b");
    await fs.mkdir(home, { recursive: true });
    await fs.mkdir(binDir, { recursive: true });

    const env = makeIsolatedEnv(home, [binDir]);
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginA, "--bin-shim-dir", binDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    // Point agy-fast-mcp to pluginB while keeping agy-fast pointing to pluginA
    execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "install", "--target", pluginB, "--no-enable"],
      { env, encoding: "utf8" },
    );
    const mcpShim = path.join(binDir, shimFileName("agy-fast-mcp"));
    await fs.unlink(mcpShim);
    const pluginBMcpTarget = path.join(pluginB, "dist", "mcp-server.mjs");
    if (IS_WIN) {
      await fs.writeFile(mcpShim, helpers.renderWindowsCmdShim(pluginBMcpTarget), "utf8");
    } else {
      await fs.symlink(pluginBMcpTarget, mcpShim);
    }

    // Place an unrelated file in the same bin directory to ensure uninstall never touches it
    const unrelated = path.join(binDir, "other-cli");
    await fs.writeFile(unrelated, "unrelated", "utf8");

    const rmA = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "uninstall", "--target", pluginA, "--bin-shim-dir", binDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(rmA, /Removed agy-fast from /);
    assert.match(rmA, /Removed bin shim\(s\) from .*agy-fast(?:\.cmd)?$/m);

    // pluginA's agy-fast shim was removed, while pluginB's agy-fast-mcp shim & unrelated file survived
    await assert.rejects(fs.lstat(path.join(binDir, shimFileName("agy-fast"))));
    assert.ok(await fs.lstat(mcpShim));
    assert.equal(await fs.readFile(unrelated, "utf8"), "unrelated");

    // Also cleans up dangling shims pointing to an already-deleted pluginDir
    await fs.rm(pluginB, { recursive: true, force: true });
    const rmDangling = execFileSync(
      process.execPath,
      [INSTALL_SCRIPT, "uninstall", "--target", pluginB, "--bin-shim-dir", binDir, "--no-enable"],
      { env, encoding: "utf8" },
    );
    assert.match(rmDangling, /Removed bin shim\(s\) from .*agy-fast-mcp(?:\.cmd)?/);
    await assert.rejects(fs.lstat(mcpShim));
  });

  it("validates --bin-shim-dir and rejects unsupported command combinations", async () => {
    const home = path.join(tmpRoot, "case-validate-home");
    await fs.mkdir(home, { recursive: true });
    const env = makeIsolatedEnv(home);

    for (const args of [
      ["install", "--bin-shim-dir"],
      ["install", "--bin-shim-dir", "--no-enable"],
      ["install", "--bin-shim-dir="],
    ]) {
      const res = runInstaller(args, env);
      assert.notEqual(res.status, 0);
      assert.match(res.stderr, /Missing directory path after --bin-shim-dir/);
    }

    for (const cmd of ["config", "mcp-config"]) {
      const res = runInstaller([cmd, "--bin-shim"], env);
      assert.notEqual(res.status, 0);
      assert.match(res.stderr, /only supported with install, update, status, doctor, and uninstall/);
    }
  });
});