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.

115 KB
Raw Blame
#!/usr/bin/env node
import { spawn, spawnSync } from "node:child_process";
import crypto from "node:crypto";
import fsSync, { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { createInterface } from "node:readline/promises";
import { fileURLToPath, pathToFileURL } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, "..");
const PLUGIN_NAME = "agy-fast";
const EXPECTED_MCP_TOOLS = [
  "batch_search",
  "apply_edits",
  "read_slices",
  "quick_outline",
  "run_checks",
];
const SUPPORTED_MCP_CONFIG_HOSTS = [
  "mcp-only",
  "json",
  "generic",
  "antigravity",
];
const MAX_LOCAL_RULE_BYTES = 256 * 1024;
const BIN_SHIM_MARKER = "agy-fast-bin-shim";
const MAX_BIN_SHIM_WRAPPER_BYTES = 8 * 1024;
const BIN_SHIM_SPECS = [
  { name: "agy-fast", relTarget: path.join("scripts", "install.mjs") },
  { name: "agy-fast-mcp", relTarget: path.join("dist", "mcp-server.mjs") },
];

const RUNTIME_FILES = [
  "plugin.json",
  "mcp_config.json",
  "hooks.json",
  "rules/AGENTS.md",
  "assets/logo.svg",
  "dist/mcp-server.mjs",
  "dist/session-start.mjs",
  "dist/benchmark.mjs",
  "dist/updater.mjs",
  "scripts/install.mjs",
  "LICENSE",
];

const OPTIONAL_DOC_FILES = [
  "assets/logo-light.svg",
  "assets/logo-dark.svg",
  "assets/architecture-light.svg",
  "assets/architecture-dark.svg",
  "assets/architecture-zh-light.svg",
  "assets/architecture-zh-dark.svg",
  "README.md",
  "README.zh-CN.md",
  "README.zh-TW.md",
  "README.ja.md",
  "CHANGELOG.md",
  "docs/ANALYSIS_REPORT.md",
  "docs/ANALYSIS_REPORT.zh-CN.md",
  "docs/SAFETY_MONITOR_ANALYSIS.md",
  "docs/SAFETY_MONITOR_ANALYSIS.zh-CN.md",
];

function getHomeDir() {
  if (process.platform === "win32") {
    const driveHome =
      process.env.HOMEDRIVE && process.env.HOMEPATH
        ? `${process.env.HOMEDRIVE}${process.env.HOMEPATH}`
        : "";
    return process.env.USERPROFILE || driveHome || process.env.HOME || os.homedir();
  }
  return process.env.HOME || process.env.USERPROFILE || os.homedir();
}

function compareSemverSimple(a, b) {
  const pa = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(a || "").trim());
  const pb = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(b || "").trim());
  if (!pa || !pb) return null;
  for (let i = 1; i <= 3; i++) {
    const na = Number.parseInt(pa[i], 10);
    const nb = Number.parseInt(pb[i], 10);
    if (na !== nb) return na > nb ? 1 : -1;
  }
  return 0;
}

function getGlobalPluginDir() {
  return path.join(getHomeDir(), ".gemini", "config", "plugins", PLUGIN_NAME);
}

function getUpdaterCacheDir() {
  const custom = process.env.AGY_FAST_CACHE_DIR?.trim();
  return custom
    ? path.resolve(custom)
    : path.join(getHomeDir(), ".gemini", "cache", PLUGIN_NAME);
}

async function getUpdaterStatePath(targetDir) {
  const custom = process.env.AGY_FAST_CACHE_DIR?.trim();
  const cacheDir = getUpdaterCacheDir();
  if (custom || !targetDir || !String(targetDir).trim()) {
    return path.join(cacheDir, "update-state.json");
  }
  const canonTarget = toComparePath(await canonicalizeExistingPath(targetDir));
  const canonDefault = toComparePath(await canonicalizeExistingPath(getGlobalPluginDir()));
  if (canonTarget === canonDefault) {
    return path.join(cacheDir, "update-state.json");
  }
  const installKey = crypto
    .createHash("sha256")
    .update(canonTarget)
    .digest("hex")
    .slice(0, 16);
  return path.join(cacheDir, "installs", installKey, "update-state.json");
}

async function readJsonSafe(filePath) {
  try {
    const raw = await fs.readFile(filePath, "utf8");
    const parsed = JSON.parse(raw);
    return parsed && typeof parsed === "object" && !Array.isArray(parsed)
      ? parsed
      : null;
  } catch {
    return null;
  }
}

async function writeUpdaterConfigFile(patch) {
  const cacheDir = getUpdaterCacheDir();
  const cfgPath = path.join(cacheDir, "config.json");
  await fs.mkdir(cacheDir, { recursive: true });
  const existing = (await readJsonSafe(cfgPath)) || {};
  const merged = { ...existing, ...patch };
  const tmpPath = `${cfgPath}.tmp.${process.pid}.${Date.now()}`;
  await fs.writeFile(tmpPath, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
  try {
    await fs.rename(tmpPath, cfgPath);
  } catch {
    try {
      await fs.copyFile(tmpPath, cfgPath);
    } finally {
      await fs.rm(tmpPath, { force: true }).catch(() => {});
    }
  }
  return { cfgPath, config: merged };
}

function parseArgs(argv) {
  const args = argv.slice(2);
  let command = "install";
  let targetDir = "";
  let projectDir = "";
  let useLink = false;
  let skipEnable = false;
  let skipAcp = false;
  let quiet = false;
  let showHelp = false;
  let checkOnly = false;
  let promptUpdate = false;
  let skipVersion = "";
  let force = false;
  let autoUpdate = "";
  let intervalHours = null;
  let channel = "";
  let repoUrl = "";
  let editsFormat = "";
  let toolLoading = "";
  let mcpHost = "";
  let mcpToolsRaw = null;
  let schemaCompat = "";
  let printRules = false;
  let binShim = false;
  let binShimDir = "";

  const positional = [];
  for (let i = 0; i < args.length; i++) {
    const a = args[i];
    if (a === "-h" || a === "--help") {
      showHelp = true;
    } else if (a === "--link") {
      useLink = true;
    } else if (a === "--no-enable") {
      skipEnable = true;
    } else if (a === "--no-acp") {
      skipAcp = true;
    } else if (a === "--quiet" || a === "-q") {
      quiet = true;
    } else if (a === "--check") {
      checkOnly = true;
    } else if (a === "--prompt" || a === "--interactive" || a === "-i") {
      promptUpdate = true;
    } else if (a === "--skip-version") {
      const next = args[i + 1];
      if (!next || next.startsWith("-")) {
        throw new Error(
          "Missing version after --skip-version (expected e.g. 0.3.0 or 'none' to clear)",
        );
      }
      skipVersion = args[++i].trim();
    } else if (a === "--force") {
      force = true;
    } else if (a === "--auto-update") {
      const next = args[i + 1];
      if (!next || !["auto", "notify", "off"].includes(next.toLowerCase())) {
        throw new Error("Invalid value after --auto-update (expected: auto | notify | off)");
      }
      autoUpdate = args[++i].toLowerCase();
    } else if (a === "--interval") {
      const next = args[i + 1];
      const parsed = Number.parseFloat(next || "");
      if (!Number.isFinite(parsed) || parsed < 1 || parsed > 720) {
        throw new Error("Invalid value after --interval (expected hours between 1 and 720)");
      }
      intervalHours = parsed;
      i++;
    } else if (a === "--channel") {
      const next = args[i + 1];
      if (!next || !["release", "main"].includes(next.toLowerCase())) {
        throw new Error("Invalid value after --channel (expected: release | main)");
      }
      channel = args[++i].toLowerCase();
    } else if (a === "--repo") {
      const next = args[i + 1];
      if (!next || next.startsWith("-")) {
        throw new Error("Missing repository URL after --repo");
      }
      repoUrl = args[++i];
    } else if (a === "--edits-format") {
      const next = args[i + 1];
      if (!next || !["auto", "array", "string"].includes(next.toLowerCase())) {
        throw new Error(
          "Invalid value after --edits-format (expected: auto | array | string)",
        );
      }
      editsFormat = args[++i].toLowerCase();
    } else if (a === "--tool-loading") {
      const next = args[i + 1];
      if (!next || !["eager", "lazy"].includes(next.toLowerCase())) {
        throw new Error(
          "Invalid value after --tool-loading (expected: eager | lazy)",
        );
      }
      toolLoading = args[++i].toLowerCase();
    } else if (a === "--host" || a.startsWith("--host=")) {
      const next = a.startsWith("--host=") ? a.slice("--host=".length) : args[i + 1];
      if (!next || (!a.startsWith("--host=") && next.startsWith("-"))) {
        throw new Error(
          `Missing value after --host (expected: ${SUPPORTED_MCP_CONFIG_HOSTS.join(" | ")})`,
        );
      }
      if (!a.startsWith("--host=")) i++;
      const normalizedHost = next.trim().toLowerCase();
      if (!SUPPORTED_MCP_CONFIG_HOSTS.includes(normalizedHost)) {
        throw new Error(
          `Invalid value after --host '${next}' (expected: ${SUPPORTED_MCP_CONFIG_HOSTS.join(" | ")})`,
        );
      }
      mcpHost = normalizedHost;
    } else if (a === "--tools" || a.startsWith("--tools=")) {
      const next = a.startsWith("--tools=") ? a.slice("--tools=".length) : args[i + 1];
      if (next === undefined || (!a.startsWith("--tools=") && next.startsWith("-"))) {
        throw new Error(
          `Missing value after --tools (valid tools: ${EXPECTED_MCP_TOOLS.join(", ")})`,
        );
      }
      if (!a.startsWith("--tools=")) i++;
      mcpToolsRaw = next;
    } else if (a === "--schema-compat" || a.startsWith("--schema-compat=")) {
      const next = a.startsWith("--schema-compat=")
        ? a.slice("--schema-compat=".length)
        : args[i + 1];
      if (!next || (!a.startsWith("--schema-compat=") && next.startsWith("-"))) {
        throw new Error(
          "Missing value after --schema-compat (expected: standard | minimal)",
        );
      }
      if (!a.startsWith("--schema-compat=")) i++;
      const normalizedCompat = next.trim().toLowerCase();
      if (!["standard", "minimal"].includes(normalizedCompat)) {
        throw new Error(
          `Invalid value after --schema-compat '${next}' (expected: standard | minimal)`,
        );
      }
      schemaCompat = normalizedCompat;
    } else if (a === "--rules") {
      printRules = true;
    } else if (a === "--bin-shim") {
      binShim = true;
    } else if (a === "--bin-shim-dir" || a.startsWith("--bin-shim-dir=")) {
      const next = a.startsWith("--bin-shim-dir=")
        ? a.slice("--bin-shim-dir=".length)
        : args[i + 1];
      if (!next || !next.trim() || (!a.startsWith("--bin-shim-dir=") && next.startsWith("-"))) {
        throw new Error("Missing directory path after --bin-shim-dir");
      }
      if (!a.startsWith("--bin-shim-dir=")) i++;
      binShimDir = path.resolve(expandHomePrefix(next.trim()));
      binShim = true;
    } else if (a === "--target") {
      const next = args[i + 1];
      if (!next || next.startsWith("-")) {
        throw new Error("Missing directory path after --target");
      }
      targetDir = path.resolve(args[++i]);
    } else if (a === "--project") {
      const next = args[i + 1];
      if (next && !next.startsWith("-")) {
        projectDir = path.resolve(args[++i]);
      } else {
        projectDir = process.cwd();
      }
    } else if (!a.startsWith("-")) {
      positional.push(a);
    } else {
      throw new Error(`Unknown option: ${a}`);
    }
  }

  if (positional.length > 1) {
    throw new Error(
      `Unexpected extra argument: '${positional[1]}'. Run with --help for usage.`,
    );
  }
  if (positional.length === 1) {
    command = positional[0];
  }

  const isCustomTarget = Boolean(targetDir);
  if (!targetDir) {
    targetDir = projectDir
      ? path.join(projectDir, ".agents", "plugins", PLUGIN_NAME)
      : getGlobalPluginDir();
  }

  return {
    command,
    targetDir,
    isProject: Boolean(projectDir),
    isCustomTarget,
    useLink,
    skipEnable,
    skipAcp,
    quiet,
    showHelp,
    checkOnly,
    promptUpdate,
    skipVersion,
    force,
    autoUpdate,
    intervalHours,
    channel,
    repoUrl,
    editsFormat,
    toolLoading,
    mcpHost,
    mcpToolsRaw,
    schemaCompat,
    printRules,
    binShim,
    binShimDir,
  };
}

function printHelp() {
  console.log(`agy-fast installer

Usage:
  node scripts/install.mjs [command] [options]

Commands:
  install      Install agy-fast plugin (default)
  update       Check for and apply plugin updates from GitHub releases
  config       View or persist auto-update preferences
  mcp-config   Print standard MCP JSON config snippet (or generic rules via --rules)
  uninstall    Remove installed agy-fast plugin
  status       Check installation and run live health checks
  doctor       Alias for status
  mcp          Start standalone MCP stdio server (forwards extra args)

Options:
  --project [dir]               Install/update <dir>/.agents/plugins/agy-fast
  --target <dir>                Use a custom plugin directory
  --link                        Create a symlink to this repository (dev mode)
  --bin-shim                    (install/update) Expose agy-fast & agy-fast-mcp in an existing user PATH dir (e.g. ~/.local/bin)
  --bin-shim-dir <dir>          Install, inspect, or remove bin shims in <dir> (implies --bin-shim)
  --no-enable                   Skip running 'agy plugin enable agy-fast'
  --no-acp                      Skip syncing isolated T3 Code ACP / GEMINI_HOME profiles
  --check                       (update) Check for newer versions without applying
  --prompt, --interactive, -i   (update) Check GitHub and ask before updating ([y]es/[n]o/[s]kip)
  --skip-version <ver|none>     (update) Skip notifications/auto-updates for a version ('none' clears)
  --force                       (update) Re-apply even if already on the same version
  --auto-update notify|auto|off Configure background update mode (default notify)
  --interval <hours>            Configure background check interval in hours (default 4)
  --channel release|main        Configure update channel (default release)
  --repo <url>                  Override git repository URL for updates
  --edits-format auto|array|string
                                Configure apply_edits.edits schema preference (default auto)
  --tool-loading eager|lazy     Configure MCP tool loading mode in mcp_config.json (default eager)
  --host <target>               (mcp-config) Target JSON format: mcp-only | json | generic | antigravity
  --schema-compat standard|minimal
                                (mcp-config) Include --schema-compat=minimal in emitted args
  --tools <list>                (mcp-config) Comma-separated tool subset for server args and rules
  --rules                       (mcp-config) Print host-agnostic Markdown routing rules
  -h, --help                    Show this help
`);
}

function checkNodeVersion() {
  const major = Number.parseInt(process.versions.node.split(".")[0] || "0", 10);
  if (major < 20) {
    throw new Error(
      `Node.js >= 20 is required (current version: v${process.versions.node})`,
    );
  }
  return process.versions.node;
}

function spawnCliSync(bin, args, opts = {}) {
  const baseOpts = { windowsHide: true, ...opts };
  const direct = spawnSync(bin, args, baseOpts);
  if (process.platform !== "win32" || direct.error?.code !== "ENOENT") {
    return direct;
  }
  const whereRes = spawnSync("where.exe", [bin], {
    encoding: "utf8",
    timeout: 2000,
    windowsHide: true,
  });
  if (whereRes.error || whereRes.status !== 0) {
    return direct;
  }
  const candidates = (whereRes.stdout || "")
    .split(/\r?\n/)
    .map((l) => l.trim())
    .filter(Boolean);
  const resolved = candidates.find((p) => /\.(exe|cmd|bat)$/i.test(p));
  if (!resolved) {
    return direct;
  }
  if (/\.exe$/i.test(resolved)) {
    return spawnSync(resolved, args, baseOpts);
  }
  const quoteWin = (s) => `"${String(s).replace(/"/g, '""')}"`;
  const cmdLine = [quoteWin(resolved), ...args.map(quoteWin)].join(" ");
  return spawnSync("cmd.exe", ["/d", "/s", "/c", `"${cmdLine}"`], {
    ...baseOpts,
    windowsVerbatimArguments: true,
  });
}

function hasCommand(bin, args = ["--version"]) {
  const res = spawnCliSync(bin, args, {
    stdio: "ignore",
    timeout: 3000,
  });
  return !res.error && res.status === 0;
}

async function pathExists(p) {
  try {
    await fs.lstat(p);
    return true;
  } catch {
    return false;
  }
}

async function lstatSafe(p, fsOps = fs) {
  try {
    return await fsOps.lstat(p);
  } catch (err) {
    if (err?.code === "ENOENT" || err?.code === "ENOTDIR") {
      return null;
    }
    throw err;
  }
}

async function statSafe(p) {
  try {
    return await fs.stat(p);
  } catch (err) {
    if (err?.code === "ENOENT" || err?.code === "ENOTDIR") {
      return null;
    }
    throw err;
  }
}

function expandHomePrefix(rawPath) {
  const trimmed = String(rawPath || "").trim();
  if (!trimmed) return "";
  const home = getHomeDir();
  if (trimmed === "~") return home;
  if (
    trimmed.startsWith("~/") ||
    (process.platform === "win32" && trimmed.startsWith("~\\"))
  ) {
    return path.join(home, trimmed.slice(2));
  }
  return trimmed;
}

function getDefaultBinShimDirs() {
  const home = getHomeDir();
  return [path.join(home, ".local", "bin"), path.join(home, "bin")];
}

async function parsePathEntries() {
  const rawPath =
    process.env.PATH || (process.platform === "win32" ? process.env.Path || "" : "");
  const compareSet = new Set();
  for (const raw of rawPath.split(path.delimiter)) {
    let entry = raw.trim();
    if (!entry) continue;
    if (
      process.platform === "win32" &&
      entry.startsWith('"') &&
      entry.endsWith('"') &&
      entry.length >= 2
    ) {
      entry = entry.slice(1, -1).trim();
    }
    entry = expandHomePrefix(entry);
    if (!entry || !path.isAbsolute(entry)) continue;
    compareSet.add(toComparePath(await canonicalizeExistingPath(entry)));
  }
  return compareSet;
}

async function isDirOnPath(dirPath, pathCompareSet) {
  const compare = toComparePath(await canonicalizeExistingPath(dirPath));
  return pathCompareSet.has(compare);
}

function getBinShimFileName(baseName) {
  return process.platform === "win32" ? `${baseName}.cmd` : baseName;
}

function escapePosixSingleQuoted(str) {
  return String(str).replace(/'/g, "'\\''");
}

function renderPosixShimWrapper(targetScriptPath) {
  const quotedTarget = `'${escapePosixSingleQuoted(targetScriptPath)}'`;
  return [
    "#!/usr/bin/env sh",
    `# ${BIN_SHIM_MARKER}`,
    `# agy-fast-target: ${JSON.stringify(targetScriptPath)}`,
    `exec node ${quotedTarget} "$@"`,
    "",
  ].join("\n");
}

function toAsciiJsonString(str) {
  return JSON.stringify(String(str)).replace(/[^\x20-\x7e]|[%!]/g, (ch) => {
    return `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`;
  });
}

function toWindowsCmdJsString(str) {
  let out = "";
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    if (
      code < 0x20 ||
      code > 0x7e ||
      code === 0x21 || // !
      code === 0x22 || // "
      code === 0x25 || // %
      code === 0x26 || // &
      code === 0x27 || // '
      code === 0x3c || // <
      code === 0x3e || // >
      code === 0x5c || // \
      code === 0x5e || // ^
      code === 0x7c    // |
    ) {
      out += `\\u${code.toString(16).padStart(4, "0")}`;
    } else {
      out += str[i];
    }
  }
  return out;
}

function renderWindowsCmdShim(targetScriptPath) {
  const raw = String(targetScriptPath);
  if (/[\r\n\0"]/.test(raw)) {
    throw new Error(`Unsafe character in Windows shim target path: ${raw}`);
  }
  // Emit an ASCII-only node -e trampoline when targetScriptPath contains non-ASCII
  // characters (e.g. CJK %USERPROFILE%) so cmd.exe OEM codepages cannot mangle UTF-8.
  // Keep @node as the final line without trailing @endlocal so exit codes and
  // self-uninstall (deleting agy-fast.cmd while running) work cleanly.
  if (/[^\x20-\x7e]/.test(raw)) {
    const jsEscaped = toWindowsCmdJsString(raw);
    const trampoline =
      `const p='${jsEscaped}';` +
      "process.argv=[process.argv[0],p,...process.argv.slice(1)];" +
      "import('node:url').then(function(u){return import(u.pathToFileURL(p).href);})" +
      ".catch(function(e){console.error(e);process.exit(1);});";
    return [
      `@rem ${BIN_SHIM_MARKER}`,
      `@rem agy-fast-target: ${toAsciiJsonString(raw)}`,
      "@setlocal DisableDelayedExpansion",
      `@node -e "${trampoline}" -- %*`,
      "",
    ].join("\r\n");
  }
  const escaped = raw.replace(/%/g, "%%");
  return [
    `@rem ${BIN_SHIM_MARKER}`,
    "@setlocal DisableDelayedExpansion",
    `@node "${escaped}" %*`,
    "",
  ].join("\r\n");
}

function parseShimWrapper(content) {
  const lines = content.split(/\r?\n/).map((l) => l.trim());
  const hasMarker = lines.some(
    (l) =>
      /^#[ \t]*agy-fast-bin-shim$/i.test(l) ||
      /^@?rem[ \t]+agy-fast-bin-shim$/i.test(l),
  );
  if (!hasMarker) {
    return { hasMarker: false, targetPath: null };
  }
  for (const line of lines) {
    const targetMetaMatch = /^(?:#|@?rem)[ \t]+agy-fast-target:/i.exec(line);
    if (targetMetaMatch) {
      const rawJson = line.slice(targetMetaMatch[0].length).trim();
      try {
        const parsed = JSON.parse(rawJson);
        if (typeof parsed === "string" && parsed) {
          return { hasMarker: true, targetPath: parsed };
        }
      } catch {
        // Ignore malformed metadata line and continue checking command line
      }
    }
    const cmdMatch = /^@?node[ \t]+"([^"]+)"[ \t]+%\*$/.exec(line);
    if (cmdMatch) {
      return { hasMarker: true, targetPath: cmdMatch[1].replace(/%%/g, "%") };
    }
    const evalMatch = /^@?node[ \t]+-e[ \t]+"const p='([^']+)';/.exec(line);
    if (evalMatch) {
      try {
        const parsed = JSON.parse(`"${evalMatch[1]}"`);
        if (typeof parsed === "string" && parsed) {
          return { hasMarker: true, targetPath: parsed };
        }
      } catch {
        // Ignore malformed trampoline path literal
      }
    }
    if (line.startsWith("exec node '") && line.endsWith("' \"$@\"")) {
      const inner = line.slice("exec node '".length, -"' \"$@\"".length);
      return { hasMarker: true, targetPath: inner.replace(/'\\''/g, "'") };
    }
  }
  return { hasMarker: true, targetPath: null };
}

function toCompareSegment(seg) {
  return process.platform === "win32" || process.platform === "darwin"
    ? seg.toLowerCase()
    : seg;
}

function isInsideNodeModules(targetPath) {
  if (!targetPath) return false;
  const normalized = path.normalize(String(targetPath));
  const segments = normalized.split(/[\\/]+/).filter(Boolean);
  return segments.some((seg) => toCompareSegment(seg) === "node_modules");
}

function pathMatchesRelTarget(candidatePath, relTarget) {
  const parts = relTarget.split(/[\\/]/);
  if (parts.length !== 2) return false;
  const fileName = path.basename(candidatePath);
  const parentDir = path.dirname(candidatePath);
  if (parentDir === candidatePath) return false;
  const parentName = path.basename(parentDir);
  return (
    toCompareSegment(parentName) === toCompareSegment(parts[0]) &&
    toCompareSegment(fileName) === toCompareSegment(parts[1])
  );
}

async function inspectPluginDirOwnership(pluginRoot) {
  const manifest = await readJsonSafe(path.join(pluginRoot, "plugin.json"));
  if (manifest && typeof manifest.name === "string") {
    return manifest.name === PLUGIN_NAME ? "agy-fast" : "other";
  }
  const pkg = await readJsonSafe(path.join(pluginRoot, "package.json"));
  if (pkg && typeof pkg.name === "string") {
    return pkg.name === PLUGIN_NAME ? "agy-fast" : "other";
  }
  return (await isDirSafe(pluginRoot)) ? "unknown-dir" : "missing";
}

async function inspectBinShim(binDir, spec) {
  const fileName = getBinShimFileName(spec.name);
  const shimPath = path.join(binDir, fileName);
  const stat = await lstatSafe(shimPath);
  if (!stat) {
    return {
      spec,
      fileName,
      shimPath,
      status: "absent",
      owned: false,
      kind: null,
      targetPath: null,
      pluginDir: null,
    };
  }

  if (stat.isSymbolicLink()) {
    let linkTarget;
    try {
      linkTarget = await fs.readlink(shimPath);
    } catch {
      return {
        spec,
        fileName,
        shimPath,
        status: "foreign",
        owned: false,
        kind: "symlink",
        targetPath: null,
        pluginDir: null,
      };
    }
    const resolvedTarget = path.resolve(path.dirname(shimPath), linkTarget);
    if (!pathMatchesRelTarget(resolvedTarget, spec.relTarget)) {
      return {
        spec,
        fileName,
        shimPath,
        status: "foreign",
        owned: false,
        kind: "symlink",
        targetPath: resolvedTarget,
        pluginDir: null,
      };
    }
    const pluginDir = path.dirname(path.dirname(resolvedTarget));
    const realPluginDir = await canonicalizeExistingPath(pluginDir);
    const realTargetPath = await canonicalizeExistingPath(resolvedTarget);
    if (
      isInsideNodeModules(pluginDir) ||
      isInsideNodeModules(realPluginDir) ||
      isInsideNodeModules(realTargetPath)
    ) {
      return {
        spec,
        fileName,
        shimPath,
        status: "foreign",
        owned: false,
        kind: "symlink",
        targetPath: resolvedTarget,
        pluginDir: null,
      };
    }
    const ownership = await inspectPluginDirOwnership(pluginDir);
    if (ownership === "other" || ownership === "unknown-dir") {
      return {
        spec,
        fileName,
        shimPath,
        status: "foreign",
        owned: false,
        kind: "symlink",
        targetPath: resolvedTarget,
        pluginDir: null,
      };
    }
    const targetStat = await statSafe(resolvedTarget);
    const isExecutable =
      process.platform === "win32" ||
      Boolean(targetStat && (targetStat.mode & 0o111) !== 0);
    const ok = ownership === "agy-fast" && Boolean(targetStat?.isFile()) && isExecutable;
    return {
      spec,
      fileName,
      shimPath,
      status: ok ? "ok" : "broken",
      owned: true,
      kind: "symlink",
      targetPath: resolvedTarget,
      pluginDir,
    };
  }

  if (stat.isFile() && stat.size <= MAX_BIN_SHIM_WRAPPER_BYTES) {
    let content = "";
    try {
      content = await fs.readFile(shimPath, "utf8");
    } catch {
      content = "";
    }
    const parsed = parseShimWrapper(content);
    if (parsed.hasMarker) {
      const targetPath = parsed.targetPath ? path.resolve(parsed.targetPath) : null;
      const pluginDir =
        targetPath && pathMatchesRelTarget(targetPath, spec.relTarget)
          ? path.dirname(path.dirname(targetPath))
          : null;
      const targetStat = targetPath ? await statSafe(targetPath) : null;
      const isWrapperExec =
        process.platform === "win32" || (stat.mode & 0o111) !== 0;
      const ok = Boolean(pluginDir && targetStat?.isFile() && isWrapperExec);
      return {
        spec,
        fileName,
        shimPath,
        status: ok ? "ok" : "broken",
        owned: true,
        kind: "wrapper",
        targetPath,
        pluginDir,
      };
    }
  }

  return {
    spec,
    fileName,
    shimPath,
    status: "foreign",
    owned: false,
    kind: stat.isFile() ? "file" : "other",
    targetPath: null,
    pluginDir: null,
  };
}

async function writeFileAtomically(filePath, content, mode = null, fsOps = fs) {
  const dir = path.dirname(filePath);
  const base = path.basename(filePath);
  const tmpPath = path.join(
    dir,
    `.${base}.agy-tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
  );
  try {
    await fsOps.writeFile(tmpPath, content, "utf8");
    if (mode !== null && process.platform !== "win32") {
      await fsOps.chmod(tmpPath, mode);
    }
    try {
      await fsOps.rename(tmpPath, filePath);
    } catch (renameErr) {
      const existingStat = await lstatSafe(filePath, fsOps);
      if (existingStat?.isSymbolicLink()) {
        // Never follow an existing symlink (e.g. an older bin shim pointing into
        // <pluginDir>/scripts/install.mjs or dist/mcp-server.mjs) via copyFile.
        try {
          await fsOps.unlink(filePath);
        } catch (unlinkErr) {
          if (unlinkErr?.code !== "ENOENT") {
            throw unlinkErr;
          }
        }
        try {
          await fsOps.rename(tmpPath, filePath);
          return;
        } catch {
          // If rename still fails after unlinking, create exclusively so a raced
          // symlink can never be followed or overwritten.
          const openFlags =
            fsSync.constants.O_WRONLY |
            fsSync.constants.O_CREAT |
            fsSync.constants.O_EXCL;
          const fh = await fsOps.open(filePath, openFlags, mode ?? 0o666);
          try {
            await fh.writeFile(content, "utf8");
            if (mode !== null && process.platform !== "win32") {
              await fh.chmod(mode);
            }
          } finally {
            await fh.close();
          }
          return;
        }
      }
      // Restrict in-place copyFile fallback strictly to locked regular files on Windows
      // (e.g. a currently-executing .cmd shim); rethrow on POSIX or non-regular targets.
      const isWinLockedRegularFile =
        process.platform === "win32" &&
        existingStat?.isFile() &&
        (isLockedTargetError(renameErr) || renameErr?.code === "EACCES");
      if (!isWinLockedRegularFile) {
        throw renameErr;
      }
      await fsOps.copyFile(tmpPath, filePath);
    }
  } finally {
    await fsOps.rm(tmpPath, { force: true }).catch(() => {});
  }
}

async function createPosixSymlinkAtomically(targetPath, linkPath) {
  const dir = path.dirname(linkPath);
  const base = path.basename(linkPath);
  const tmpLink = path.join(
    dir,
    `.${base}.agy-tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
  );
  try {
    await fs.symlink(targetPath, tmpLink);
    await fs.rename(tmpLink, linkPath);
  } finally {
    await fs.rm(tmpLink, { force: true }).catch(() => {});
  }
}

async function installBinShims(resolvedPluginDir, opts) {
  if (opts.isProject && !opts.binShimDir) {
    if (!opts.quiet) {
      console.log(
        "Note: skipped --bin-shim for --project install (pass --bin-shim-dir <dir> to install shims for a project-local plugin).",
      );
    }
    return { attempted: false, binDir: null, installed: [], skipped: [] };
  }

  const pathCompareSet = await parsePathEntries();
  let binDir = opts.binShimDir;
  let onPath = false;
  if (binDir) {
    await fs.mkdir(binDir, { recursive: true });
    onPath = await isDirOnPath(binDir, pathCompareSet);
  } else {
    const candidates = getDefaultBinShimDirs();
    for (const candidate of candidates) {
      if ((await isDirSafe(candidate)) && (await isDirOnPath(candidate, pathCompareSet))) {
        binDir = candidate;
        onPath = true;
        break;
      }
    }
    if (!binDir) {
      if (!opts.quiet) {
        const existingCandidates = [];
        for (const candidate of candidates) {
          if (await isDirSafe(candidate)) {
            existingCandidates.push(candidate);
          }
        }
        const primaryDefault = candidates[0];
        if (existingCandidates.length > 0) {
          console.log(
            `Note: skipped --bin-shim because ${existingCandidates.join(" / ")} is not on PATH.`,
          );
          console.log(
            `      Add ${existingCandidates[0]} to PATH and re-run with --bin-shim, or pass --bin-shim-dir <dir>.`,
          );
        } else {
          console.log(
            `Note: skipped --bin-shim because no existing user bin directory on PATH was found (checked: ${candidates.join(", ")}).`,
          );
          console.log(
            `      Create ${primaryDefault} and add it to PATH, or pass --bin-shim-dir <dir>.`,
          );
        }
      }
      return { attempted: false, binDir: null, installed: [], skipped: [] };
    }
  }

  const installed = [];
  const skipped = [];
  const targetPluginCompare = await canonicalizeEntryComparePath(resolvedPluginDir);
  for (const spec of BIN_SHIM_SPECS) {
    const targetScriptPath = path.join(resolvedPluginDir, spec.relTarget);
    const targetStat = await statSafe(targetScriptPath);
    if (!targetStat?.isFile()) {
      throw new Error(`Cannot create bin shim '${spec.name}': missing ${targetScriptPath}`);
    }
    const existing = await inspectBinShim(binDir, spec);
    if (existing.status !== "absent" && !existing.owned) {
      skipped.push(existing);
      if (!opts.quiet) {
        console.warn(
          `Warning: skipped bin shim ${existing.shimPath}: existing file or symlink is not managed by ${PLUGIN_NAME}.`,
        );
      }
      continue;
    }

    if (process.platform === "win32") {
      await writeFileAtomically(existing.shimPath, renderWindowsCmdShim(targetScriptPath));
      installed.push({ name: existing.fileName, path: existing.shimPath, mode: "cmd" });
    } else {
      if ((targetStat.mode & 0o111) === 0) {
        await fs.chmod(targetScriptPath, 0o755);
      }
      const alreadyMatchingSymlink =
        existing.kind === "symlink" &&
        existing.status === "ok" &&
        existing.pluginDir &&
        (await canonicalizeEntryComparePath(existing.pluginDir)) === targetPluginCompare;
      if (alreadyMatchingSymlink) {
        installed.push({ name: existing.fileName, path: existing.shimPath, mode: "symlink" });
        continue;
      }
      let shimMode = "symlink";
      try {
        await createPosixSymlinkAtomically(targetScriptPath, existing.shimPath);
      } catch (err) {
        const code = err?.code;
        if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV") {
          await writeFileAtomically(
            existing.shimPath,
            renderPosixShimWrapper(targetScriptPath),
            0o755,
          );
          shimMode = "wrapper";
        } else {
          throw err;
        }
      }
      installed.push({ name: existing.fileName, path: existing.shimPath, mode: shimMode });
    }
  }

  if (!opts.quiet) {
    if (installed.length > 0) {
      console.log(
        `Installed bin shim(s) in ${binDir}: ${installed.map((i) => i.name).join(", ")}`,
      );
    }
    if (opts.binShimDir && !onPath) {
      console.log(
        `Note: ${binDir} is not currently on PATH; add it to PATH or invoke ${path.join(binDir, getBinShimFileName("agy-fast"))} directly.`,
      );
    }
  }
  return { attempted: true, binDir, onPath, installed, skipped };
}

async function collectBinShimStatuses(targetDir, binShimDir = "") {
  const dirs = binShimDir ? [binShimDir] : getDefaultBinShimDirs();
  const targetCompare = await canonicalizeEntryComparePath(targetDir);
  const dirReports = [];

  for (const dir of dirs) {
    const dirExists = await isDirSafe(dir);
    if (!dirExists && !binShimDir) continue;
    const entries = [];
    if (dirExists) {
      for (const spec of BIN_SHIM_SPECS) {
        const info = await inspectBinShim(dir, spec);
        const pluginCompare = info.pluginDir
          ? await canonicalizeEntryComparePath(info.pluginDir)
          : null;
        entries.push({ ...info, pluginCompare });
      }
    }
    const owned = entries.filter((e) => e.owned);
    const foreign = entries.filter((e) => e.status === "foreign");
    if (owned.length === 0 && !binShimDir) {
      continue;
    }
    const broken = owned.filter((e) => e.status === "broken");
    const okEntries = owned.filter((e) => e.status === "ok");
    const otherTargets = [
      ...new Set(
        okEntries
          .filter((e) => e.pluginCompare && e.pluginCompare !== targetCompare)
          .map((e) => e.pluginDir),
      ),
    ];
    let status = "none";
    if (broken.length > 0) {
      status = "broken";
    } else if (okEntries.length > 0) {
      status = "ok";
    }
    dirReports.push({
      binDir: dir,
      dirExists,
      status,
      owned,
      okEntries,
      broken,
      foreign,
      otherTargets,
    });
  }
  return dirReports;
}

async function findMatchingBinShims(targetPluginDir, binShimDir = "") {
  const dirs = binShimDir ? [binShimDir] : getDefaultBinShimDirs();
  const targetCompare = await canonicalizeEntryComparePath(targetPluginDir);
  const matches = [];
  for (const dir of dirs) {
    if (!(await isDirSafe(dir))) continue;
    for (const spec of BIN_SHIM_SPECS) {
      const info = await inspectBinShim(dir, spec);
      if (!info.owned || !info.pluginDir) continue;
      if ((await canonicalizeEntryComparePath(info.pluginDir)) === targetCompare) {
        matches.push({ ...info, binDir: dir });
      }
    }
  }
  return matches;
}

function toComparePath(p) {
  const normalized = path.resolve(p);
  return process.platform === "win32" || process.platform === "darwin"
    ? normalized.toLowerCase()
    : normalized;
}

async function canonicalizeExistingPath(p) {
  const resolved = path.resolve(p);
  const tail = [];
  let cur = resolved;
  while (true) {
    try {
      const real = await fs.realpath(cur);
      return tail.length > 0 ? path.join(real, ...tail.reverse()) : real;
    } catch (err) {
      if (err?.code !== "ENOENT" && err?.code !== "ENOTDIR") {
        return resolved;
      }
      const parent = path.dirname(cur);
      if (parent === cur) {
        return resolved;
      }
      tail.push(path.basename(cur));
      cur = parent;
    }
  }
}

async function canonicalizeEntryComparePath(p) {
  const resolved = path.resolve(p);
  const stat = await lstatSafe(resolved);
  if (stat && !stat.isSymbolicLink()) {
    return toComparePath(await canonicalizeExistingPath(resolved));
  }
  const parent = path.dirname(resolved);
  if (parent === resolved) {
    return toComparePath(resolved);
  }
  const realParent = await canonicalizeExistingPath(parent);
  return toComparePath(path.join(realParent, path.basename(resolved)));
}

function isStrictAncestorPath(ancestorPath, descendantPath) {
  const rel = path.relative(ancestorPath, descendantPath);
  return (
    rel !== "" &&
    rel !== ".." &&
    !rel.startsWith(`..${path.sep}`) &&
    !path.isAbsolute(rel)
  );
}

async function assertRemovableTarget(targetPath, stat) {
  if (!stat || stat.isSymbolicLink()) {
    return;
  }
  if (!stat.isDirectory()) {
    throw new Error(
      `Refusing to delete ${targetPath}: target exists and is not an ${PLUGIN_NAME} directory or symlink.`,
    );
  }
  const entries = await fs.readdir(targetPath);
  if (entries.length === 0) {
    return;
  }
  const manifest = await readJsonSafe(path.join(targetPath, "plugin.json"));
  if (manifest?.name !== PLUGIN_NAME) {
    throw new Error(
      `Refusing to delete non-empty directory ${targetPath}: missing plugin.json with name "${PLUGIN_NAME}".`,
    );
  }
}

async function removeTargetPath(targetPath, stat, { quiet = false } = {}) {
  if (!stat) {
    return;
  }
  if (stat.isSymbolicLink()) {
    await fs.unlink(targetPath);
    return;
  }
  if (stat.isDirectory()) {
    // Evacuate via atomic same-parent rename first so an EBUSY/EPERM lock fails before deleting any file.
    const trashPath = path.join(
      path.dirname(targetPath),
      `.${path.basename(targetPath)}.agy-trash-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    );
    await fs.rename(targetPath, trashPath);
    try {
      await fs.rm(trashPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
    } catch (rmErr) {
      // Target path is already vacated atomically; warn instead of misclassifying post-rename cleanup errors as a target lock.
      if (!quiet) {
        console.warn(
          `Warning: removed ${targetPath}, but failed to clean up temporary staging directory ${trashPath}: ${rmErr instanceof Error ? rmErr.message : String(rmErr)}`,
        );
      }
    }
    return;
  }
  await fs.rm(targetPath, { force: true });
}

async function verifyMcpServerLive(mcpScriptPath) {
  const cleanMcpEnv = { ...process.env };
  delete cleanMcpEnv.AGY_FAST_TOOLS;
  return new Promise((resolve, reject) => {
    const child = spawn(process.execPath, [mcpScriptPath], {
      stdio: ["pipe", "pipe", "pipe"],
      windowsHide: true,
      env: cleanMcpEnv,
    });

    let stdout = "";
    let stderr = "";
    const timer = setTimeout(() => {
      child.kill("SIGKILL");
      reject(new Error("MCP server smoke test timed out after 5s"));
    }, 5000);
    timer.unref();

    child.stdout.on("data", (d) => {
      stdout += d.toString("utf8");
    });
    child.stderr.on("data", (d) => {
      stderr += d.toString("utf8");
    });
    child.on("error", (err) => {
      clearTimeout(timer);
      reject(err);
    });
    child.on("close", (code) => {
      clearTimeout(timer);
      const lines = stdout
        .split(/\r?\n/)
        .map((l) => l.trim())
        .filter(Boolean);
      if (lines.length < 2) {
        reject(
          new Error(
            `MCP server returned incomplete response (exit ${code}): ${stderr || stdout}`,
          ),
        );
        return;
      }
      try {
        const initResp = JSON.parse(lines[0]);
        const listResp = JSON.parse(lines[1]);
        const tools = listResp?.result?.tools;
        if (!initResp?.result?.serverInfo || !Array.isArray(tools)) {
          reject(new Error("Invalid MCP JSON-RPC responses"));
          return;
        }
        const applyEditsTool = tools.find((t) => t.name === "apply_edits");
        const applyEditsSchemaType =
          applyEditsTool?.inputSchema?.properties?.edits?.type || "unknown";
        resolve({
          protocolVersion: initResp.result.protocolVersion,
          tools: tools.map((t) => t.name),
          applyEditsSchemaType,
        });
      } catch (err) {
        reject(err);
      }
    });

    child.stdin.write(
      JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "initialize",
        params: {
          protocolVersion: "2025-03-26",
          capabilities: {},
          clientInfo: { name: "agy-fast-doctor", version: "1.0" },
        },
      }) + "\n",
    );
    child.stdin.write(
      JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n",
    );
    child.stdin.write(
      JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }) + "\n",
    );
    child.stdin.end();
  });
}

async function verifySessionStartLive(hookScriptPath, sampleWorkspace) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    const child = spawn(process.execPath, [hookScriptPath], {
      stdio: ["pipe", "pipe", "pipe"],
      windowsHide: true,
      env: { ...process.env, AGY_FAST_AUTO_UPDATE: "off" },
    });
    let stdout = "";
    const timer = setTimeout(() => {
      child.kill("SIGKILL");
      reject(new Error("SessionStart hook smoke test timed out after 5s"));
    }, 5000);
    timer.unref();

    child.stdout.on("data", (d) => {
      stdout += d.toString("utf8");
    });
    child.on("error", (err) => {
      clearTimeout(timer);
      reject(err);
    });
    child.on("close", (code) => {
      clearTimeout(timer);
      if (code !== 0) {
        reject(new Error(`SessionStart hook exited with code ${code}`));
        return;
      }
      try {
        const parsed = JSON.parse(stdout.trim());
        const msg = parsed?.injectSteps?.[0]?.systemMessage?.systemMessage || "";
        resolve({
          durationMs: Date.now() - start,
          bytes: Buffer.byteLength(msg, "utf8"),
        });
      } catch (err) {
        reject(err);
      }
    });

    child.stdin.end(
      JSON.stringify({
        cwd: sampleWorkspace,
        workspacePaths: [sampleWorkspace],
        hookEventName: "SessionStart",
      }),
    );
  });
}

async function assertSourceFilesPresent(srcRoot) {
  for (const rel of RUNTIME_FILES) {
    const src = path.join(srcRoot, rel);
    if (!(await pathExists(src))) {
      throw new Error(
        `Missing required file: ${rel}. Run 'npm run build' first if installing from source.`,
      );
    }
  }
}

async function copyRuntimeFiles(srcRoot, dstRoot) {
  await assertSourceFilesPresent(srcRoot);
  await fs.mkdir(dstRoot, { recursive: true });
  const toCopy = [...RUNTIME_FILES];
  for (const opt of OPTIONAL_DOC_FILES) {
    if (await pathExists(path.join(srcRoot, opt))) {
      toCopy.push(opt);
    }
  }
  for (const rel of toCopy) {
    const src = path.join(srcRoot, rel);
    const dst = path.join(dstRoot, rel);
    await fs.mkdir(path.dirname(dst), { recursive: true });
    await fs.copyFile(src, dst);
  }
}

function isLockedTargetError(err) {
  const code = err?.code;
  return code === "EBUSY" || code === "EPERM";
}

function formatLockedTargetError(targetPath, err) {
  const code = err?.code || "LOCKED";
  return new Error(
    `Cannot replace ${targetPath} (${code}): target is in use by a running MCP host process. Close the running host/MCP process and retry.`,
  );
}

async function syncRuntimeFilesAtomically(srcRoot, dstRoot) {
  await assertSourceFilesPresent(srcRoot);
  await fs.mkdir(dstRoot, { recursive: true });
  // Sync plugin.json LAST so a partial failure never advances the installed version marker
  // while dist/*.mjs remain on the previous version.
  const runtimeWithoutManifest = RUNTIME_FILES.filter((rel) => rel !== "plugin.json");
  const toCopy = [...runtimeWithoutManifest];
  for (const opt of OPTIONAL_DOC_FILES) {
    if (await pathExists(path.join(srcRoot, opt))) {
      toCopy.push(opt);
    }
  }
  toCopy.push("plugin.json");

  let seq = 0;
  for (const rel of toCopy) {
    const src = path.join(srcRoot, rel);
    const dst = path.join(dstRoot, rel);
    await fs.mkdir(path.dirname(dst), { recursive: true });
    const tmp = `${dst}.agy-tmp.${process.pid}.${seq++}`;
    try {
      await fs.copyFile(src, tmp);
    } catch (err) {
      await fs.rm(tmp, { force: true }).catch(() => {});
      throw err;
    }
    try {
      await fs.rename(tmp, dst);
    } catch {
      try {
        await fs.copyFile(tmp, dst);
      } finally {
        await fs.rm(tmp, { force: true }).catch(() => {});
      }
    }
  }
}

function parseToolLoadingValue(raw) {
  if (typeof raw !== "string") return "";
  const v = raw.trim().toLowerCase();
  return v === "eager" || v === "lazy" ? v : "";
}

async function resolveEffectiveToolLoading(explicitOverride = "") {
  const explicit = parseToolLoadingValue(explicitOverride);
  if (explicit) return explicit;
  const fromEnv = parseToolLoadingValue(process.env.AGY_FAST_TOOL_LOADING || "");
  if (fromEnv) return fromEnv;
  const cfgPath = path.join(getUpdaterCacheDir(), "config.json");
  const cfg = (await readJsonSafe(cfgPath)) || {};
  return parseToolLoadingValue(cfg.toolLoading) || "eager";
}

async function applyToolLoadingToCopiedPluginDir(pluginDir, mode) {
  const dirStat = await lstatSafe(pluginDir);
  if (!dirStat) return { applied: false, reason: "missing" };
  if (dirStat.isSymbolicLink()) return { applied: false, reason: "symlink" };
  if (await pathExists(path.join(pluginDir, ".git"))) {
    return { applied: false, reason: "git-clone" };
  }
  const mcpPath = path.join(pluginDir, "mcp_config.json");
  const cfg = await readJsonSafe(mcpPath);
  if (!cfg?.mcpServers?.fast || typeof cfg.mcpServers.fast !== "object") {
    return { applied: false, reason: "invalid-mcp-config" };
  }
  if (mode === "lazy") {
    delete cfg.mcpServers.fast.tools;
  } else {
    const toolsMap = {};
    for (const tool of EXPECTED_MCP_TOOLS) {
      toolsMap[tool] = { eager: true };
    }
    cfg.mcpServers.fast.tools = toolsMap;
  }
  const tmpPath = `${mcpPath}.tmp.${process.pid}.${Date.now()}`;
  await fs.writeFile(tmpPath, `${JSON.stringify(cfg, null, 2)}\n`, "utf8");
  try {
    await fs.rename(tmpPath, mcpPath);
  } catch {
    try {
      await fs.copyFile(tmpPath, mcpPath);
    } finally {
      await fs.rm(tmpPath, { force: true }).catch(() => {});
    }
  }
  return { applied: true, reason: null };
}

async function snapshotLocalRuleFiles(pluginDir) {
  const preserved = [];
  const skipped = [];
  const dirStat = await lstatSafe(pluginDir);
  if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
    return { preserved, skipped };
  }
  const rulesDir = path.join(pluginDir, "rules");
  const rulesStat = await lstatSafe(rulesDir);
  if (!rulesStat || rulesStat.isSymbolicLink() || !rulesStat.isDirectory()) {
    return { preserved, skipped };
  }
  let entries;
  try {
    entries = await fs.readdir(rulesDir, { withFileTypes: true });
  } catch {
    return { preserved, skipped };
  }
  for (const entry of entries) {
    const name = entry.name;
    if (
      !name ||
      name.startsWith(".") ||
      !name.toLowerCase().endsWith(".local.md") ||
      name.length <= ".local.md".length ||
      name.includes("/") ||
      name.includes("\\") ||
      name.includes("\0") ||
      path.basename(name) !== name
    ) {
      continue;
    }
    const fullPath = path.join(rulesDir, name);
    const st = await lstatSafe(fullPath);
    if (!st) continue;
    if (st.isSymbolicLink()) {
      skipped.push({ name, reason: "symlink" });
      continue;
    }
    if (!st.isFile()) continue;
    if (st.size > MAX_LOCAL_RULE_BYTES) {
      skipped.push({ name, reason: `exceeds ${Math.round(MAX_LOCAL_RULE_BYTES / 1024)}KB limit` });
      continue;
    }
    try {
      const content = await fs.readFile(fullPath);
      if (content.length > MAX_LOCAL_RULE_BYTES) {
        skipped.push({ name, reason: `exceeds ${Math.round(MAX_LOCAL_RULE_BYTES / 1024)}KB limit` });
        continue;
      }
      preserved.push({ name, content, mode: (st.mode & 0o777) | 0o600 });
    } catch {
      skipped.push({ name, reason: "unreadable" });
    }
  }
  preserved.sort((a, b) => a.name.localeCompare(b.name));
  skipped.sort((a, b) => a.name.localeCompare(b.name));
  return { preserved, skipped };
}

async function restoreLocalRuleFiles(pluginDir, preserved) {
  const restored = [];
  const keptExisting = [];
  if (!preserved || preserved.length === 0) {
    return { restored, keptExisting };
  }
  const rulesDir = path.join(pluginDir, "rules");
  await fs.mkdir(rulesDir, { recursive: true });
  for (const file of preserved) {
    const dst = path.join(rulesDir, file.name);
    if (await lstatSafe(dst)) {
      keptExisting.push(file.name);
      continue;
    }
    await fs.writeFile(dst, file.content, { mode: file.mode || 0o644 });
    restored.push(file.name);
  }
  return { restored, keptExisting };
}

async function hasLocalRuleFiles(pluginDir) {
  const rulesDir = path.join(pluginDir, "rules");
  try {
    const entries = await fs.readdir(rulesDir);
    return entries.some((n) => n.toLowerCase().endsWith(".local.md"));
  } catch {
    return false;
  }
}

async function isDirSafe(p) {
  try {
    return (await fs.stat(p)).isDirectory();
  } catch {
    return false;
  }
}

async function discoverIsolatedPluginDirs(primaryGlobalDir) {
  const home = getHomeDir();
  const primaryCompare = await canonicalizeEntryComparePath(primaryGlobalDir);
  const defaultGeminiCompare = toComparePath(
    await canonicalizeExistingPath(path.join(home, ".gemini")),
  );
  const seen = new Set([primaryCompare]);
  const results = [];

  const addCandidate = async (geminiRoot, label) => {
    const resolvedRoot = path.resolve(geminiRoot);
    const rootCompare = toComparePath(await canonicalizeExistingPath(resolvedRoot));
    if (rootCompare === defaultGeminiCompare) return;
    const pluginDir = path.join(resolvedRoot, "config", "plugins", PLUGIN_NAME);
    const key = await canonicalizeEntryComparePath(pluginDir);
    if (seen.has(key)) return;
    seen.add(key);
    results.push({ geminiRoot: resolvedRoot, pluginDir, label });
  };

  // 1. T3 Code isolated Antigravity ACP provider profiles:
  //    ~/.t3/userdata/providers/antigravity/<hash>/
  const t3ProvidersRoot = path.join(home, ".t3", "userdata", "providers", "antigravity");
  try {
    const entries = await fs.readdir(t3ProvidersRoot, { withFileTypes: true });
    entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
    for (const entry of entries) {
      if (!entry.isDirectory()) continue;
      const profileRoot = path.join(t3ProvidersRoot, entry.name);
      const hasConfig = await isDirSafe(path.join(profileRoot, "config"));
      const hasAcp = await isDirSafe(path.join(profileRoot, "antigravity-acp"));
      if (hasConfig || hasAcp) {
        await addCandidate(profileRoot, `T3 Code ACP (${entry.name.slice(0, 8)})`);
      }
    }
  } catch {
    // ~/.t3 not present
  }

  // 2. Explicit GEMINI_HOME env var when pointing to an isolated Antigravity / ACP home
  const envGeminiHome = process.env.GEMINI_HOME?.trim();
  if (envGeminiHome) {
    const resolvedEnv = path.resolve(envGeminiHome);
    if (await isDirSafe(resolvedEnv)) {
      const hasConfig = await isDirSafe(path.join(resolvedEnv, "config"));
      const hasAcp = await isDirSafe(path.join(resolvedEnv, "antigravity-acp"));
      if (hasConfig || hasAcp) {
        await addCandidate(resolvedEnv, "GEMINI_HOME");
      }
    }
  }

  return results;
}

async function inspectIsolatedPluginDir(isolated) {
  const stat = await lstatSafe(isolated.pluginDir);
  if (!stat) {
    return { ...isolated, status: "missing", mode: null, linkTarget: null, version: null };
  }
  const configJson = await readJsonSafe(path.join(isolated.geminiRoot, "config", "config.json"));
  const disabledInConfig = configJson?.plugins?.[PLUGIN_NAME]?.enabled === false;
  const manifest = await readJsonSafe(path.join(isolated.pluginDir, "plugin.json"));
  const mcpExists = await pathExists(path.join(isolated.pluginDir, "dist", "mcp-server.mjs"));
  const valid = manifest?.name === PLUGIN_NAME && mcpExists;
  const version = typeof manifest?.version === "string" ? manifest.version : null;

  if (stat.isSymbolicLink()) {
    let linkTarget = null;
    try {
      linkTarget = await fs.readlink(isolated.pluginDir);
    } catch {
      // ignore
    }
    if (!valid) {
      return { ...isolated, status: "broken", mode: "symlink", linkTarget, version: null };
    }
    return {
      ...isolated,
      status: disabledInConfig ? "disabled" : "ok",
      mode: "symlink",
      linkTarget,
      version,
    };
  }

  if (!valid) {
    return { ...isolated, status: "broken", mode: "copied", linkTarget: null, version: null };
  }
  return {
    ...isolated,
    status: disabledInConfig ? "disabled" : "ok",
    mode: "copied",
    linkTarget: null,
    version,
  };
}

async function syncIsolatedPluginDir(resolvedSrc, primaryGlobalDir, isolated, opts) {
  const isoStat = await lstatSafe(isolated.pluginDir);
  const srcCompare = toComparePath(await canonicalizeExistingPath(resolvedSrc));
  const primaryStat = await lstatSafe(primaryGlobalDir);
  const primaryRealPath =
    primaryStat && !primaryStat.isSymbolicLink()
      ? await canonicalizeExistingPath(primaryGlobalDir)
      : primaryGlobalDir;
  const primaryCompare =
    primaryStat && !primaryStat.isSymbolicLink()
      ? toComparePath(primaryRealPath)
      : await canonicalizeEntryComparePath(primaryGlobalDir);
  const isoEntryCompare = await canonicalizeEntryComparePath(isolated.pluginDir);
  if (isoEntryCompare === primaryCompare) {
    return { synced: true, mode: "same" };
  }
  if (isoStat && !isoStat.isSymbolicLink()) {
    const isoCompare = toComparePath(await fs.realpath(isolated.pluginDir));
    if (isoCompare === srcCompare || isoCompare === primaryCompare) {
      return { synced: true, mode: "same" };
    }
    if (
      isStrictAncestorPath(isoCompare, srcCompare) ||
      isStrictAncestorPath(isoCompare, primaryCompare)
    ) {
      throw new Error(
        `Refusing to sync into ${isolated.pluginDir}: target is an ancestor directory of ${resolvedSrc}.`,
      );
    }
  }

  await assertRemovableTarget(isolated.pluginDir, isoStat);
  const { preserved: preservedIsoLocalRules, skipped: skippedIsoLocalRules } =
    await snapshotLocalRuleFiles(isolated.pluginDir);
  await fs.mkdir(path.dirname(isolated.pluginDir), { recursive: true });
  let mode = "symlink";
  let migratedToPrimary = { restored: [], keptExisting: [] };
  try {
    await removeTargetPath(isolated.pluginDir, isoStat, { quiet: opts.quiet });
  } catch (err) {
    if (!opts.useLink && isoStat?.isDirectory() && !isoStat.isSymbolicLink() && isLockedTargetError(err)) {
      try {
        await syncRuntimeFilesAtomically(resolvedSrc, isolated.pluginDir);
      } catch (syncErr) {
        if (isLockedTargetError(syncErr)) {
          throw formatLockedTargetError(isolated.pluginDir, syncErr);
        }
        throw syncErr;
      }
      if (opts.effectiveToolLoading) {
        await applyToolLoadingToCopiedPluginDir(isolated.pluginDir, opts.effectiveToolLoading);
      }
      await restoreLocalRuleFiles(isolated.pluginDir, preservedIsoLocalRules);
      mode = "copied-in-place";
    } else if (isLockedTargetError(err)) {
      throw formatLockedTargetError(isolated.pluginDir, err);
    } else {
      throw err;
    }
  }

  // Link directly to resolvedSrc in --link dev mode (avoids chained NTFS junctions on Windows),
  // otherwise link to primaryRealPath so auto-updates to ~/.gemini/config/plugins/agy-fast
  // propagate immediately to every isolated ACP profile.
  const linkSource = opts.useLink ? resolvedSrc : primaryRealPath;
  if (mode !== "copied-in-place") {
    const linkType = process.platform === "win32" ? "junction" : "dir";
    try {
      await fs.symlink(linkSource, isolated.pluginDir, linkType);
    } catch (err) {
      const code = err?.code;
      if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV") {
        await copyRuntimeFiles(resolvedSrc, isolated.pluginDir);
        if (opts.effectiveToolLoading) {
          await applyToolLoadingToCopiedPluginDir(isolated.pluginDir, opts.effectiveToolLoading);
        }
        await restoreLocalRuleFiles(isolated.pluginDir, preservedIsoLocalRules);
        mode = "copied";
      } else {
        throw err;
      }
    }
    if (mode === "symlink" && !opts.useLink && preservedIsoLocalRules.length > 0) {
      migratedToPrimary = await restoreLocalRuleFiles(
        primaryRealPath,
        preservedIsoLocalRules,
      );
    }
  }

  if (!opts.quiet) {
    if (mode === "symlink") {
      console.log(`Synced ${isolated.label}: ${isolated.pluginDir} -> ${linkSource}`);
      if (migratedToPrimary.restored.length > 0) {
        console.log(
          `Migrated isolated local rule file(s) to primary plugin dir: ${migratedToPrimary.restored.map((n) => `rules/${n}`).join(", ")}`,
        );
      }
      if (migratedToPrimary.keptExisting.length > 0) {
        console.log(
          `Kept existing primary local rule file(s) on symlink sync: ${migratedToPrimary.keptExisting.map((n) => `rules/${n}`).join(", ")}`,
        );
      }
      if (opts.useLink && preservedIsoLocalRules.length > 0) {
        console.log(
          `Note: --link replaced ${isolated.pluginDir}; local rule file(s) were not copied into dev checkout: ${preservedIsoLocalRules.map((f) => `rules/${f.name}`).join(", ")}`,
        );
      }
    } else if (mode === "copied-in-place") {
      console.log(
        `Note: ${isolated.pluginDir} was locked by a running process; updated files atomically in-place. Reload your host window to load the new MCP server.`,
      );
    } else {
      console.log(`Synced ${isolated.label} (copied): ${isolated.pluginDir}`);
    }
    if (skippedIsoLocalRules.length > 0) {
      console.log(
        `Skipped unsafe/oversized local rule file(s) in ${isolated.label}: ${skippedIsoLocalRules.map((s) => `rules/${s.name} (${s.reason})`).join(", ")}`,
      );
    }
    const configJson = await readJsonSafe(path.join(isolated.geminiRoot, "config", "config.json"));
    if (configJson?.plugins?.[PLUGIN_NAME]?.enabled === false) {
      console.log(
        `Note: '${PLUGIN_NAME}' is explicitly disabled in ${path.join(isolated.geminiRoot, "config", "config.json")}.`,
      );
    }
  }
  return { synced: true, mode };
}

const STORAGE_STALE_DAYS = 60;
const STORAGE_WARN_BYTES = 2 * 1024 * 1024 * 1024; // 2 GiB
const STORAGE_SCAN_BUDGET_MS = 2500;
const STORAGE_STAT_CONCURRENCY = 16;
// Verified on Antigravity Desktop v2.34-v2.36 / CLI v1.5.x (rules.go:736)
const ANTIGRAVITY_RULE_CAP_BYTES = 24_000;
const ANTIGRAVITY_RULE_NEAR_CAP_BYTES = 20_000;
const HOST_HYGIENE_SCAN_BUDGET_MS = 1000;

function formatByteSize(bytes) {
  if (bytes >= 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GiB`;
  }
  if (bytes >= 1024 * 1024) {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
  }
  if (bytes >= 1024) {
    return `${(bytes / 1024).toFixed(1)} KiB`;
  }
  return `${bytes} B`;
}

function expandHomePath(rawPath) {
  const trimmed = rawPath.trim();
  if (trimmed === "~") return getHomeDir();
  if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) {
    return path.join(getHomeDir(), trimmed.slice(2));
  }
  return trimmed;
}

async function runBoundedPool(items, concurrency, deadlineMs, worker) {
  let cursor = 0;
  let timedOut = false;
  const workerCount = Math.min(concurrency, items.length);
  const runners = Array.from({ length: workerCount }, async () => {
    while (cursor < items.length) {
      if (Date.now() >= deadlineMs) {
        timedOut = true;
        return;
      }
      const idx = cursor++;
      await worker(items[idx]);
    }
  });
  await Promise.all(runners);
  return timedOut;
}

async function inspectLocalAntigravityStorage() {
  const deadlineMs = Date.now() + STORAGE_SCAN_BUDGET_MS;
  let partial = false;
  const home = getHomeDir();
  const appDirsByKey = new Map();
  const addAppDir = async (candidate) => {
    if (!candidate) return;
    if (Date.now() >= deadlineMs) {
      partial = true;
      return;
    }
    const resolved = path.resolve(expandHomePath(candidate));
    const key = toComparePath(await canonicalizeExistingPath(resolved));
    if (!appDirsByKey.has(key)) appDirsByKey.set(key, resolved);
  };

  const geminiRootsByKey = new Map();
  for (const candidate of [
    path.join(home, ".gemini"),
    process.env.GEMINI_HOME?.trim() || "",
  ]) {
    if (!candidate) continue;
    if (Date.now() >= deadlineMs) {
      partial = true;
      break;
    }
    const resolved = path.resolve(expandHomePath(candidate));
    const key = toComparePath(await canonicalizeExistingPath(resolved));
    if (!geminiRootsByKey.has(key)) geminiRootsByKey.set(key, resolved);
  }
  for (const geminiDir of geminiRootsByKey.values()) {
    for (const sub of ["antigravity", "antigravity-cli", "antigravity-ide", "antigravity-acp"]) {
      await addAppDir(path.join(geminiDir, sub));
      if (partial) break;
    }
    if (partial) break;
  }

  // Include T3 Code isolated ACP profiles (~/.t3/userdata/providers/antigravity/*/antigravity-acp)
  if (!partial) {
    const t3ProvidersRoot = path.join(home, ".t3", "userdata", "providers", "antigravity");
    try {
      const t3Entries = await fs.readdir(t3ProvidersRoot, { withFileTypes: true });
      for (const ent of t3Entries) {
        if (Date.now() >= deadlineMs) {
          partial = true;
          break;
        }
        if (!ent.isDirectory()) continue;
        await addAppDir(path.join(t3ProvidersRoot, ent.name, "antigravity-acp"));
        if (partial) break;
      }
    } catch {
      // ~/.t3 not present
    }
  }

  // Include explicit ANTIGRAVITY_APP_DATA_DIR if configured
  const envAppData = process.env.ANTIGRAVITY_APP_DATA_DIR?.trim();
  if (!partial && envAppData) {
    await addAppDir(envAppData);
  }

  const staleCutoffMs = Date.now() - STORAGE_STALE_DAYS * 24 * 60 * 60 * 1000;
  let conversationDbBytes = 0;
  let conversationDbFiles = 0;
  let transcriptBytes = 0;
  let brainSessionDirs = 0;
  let staleSessions60d = 0;

  const seenConvDirs = new Set();
  const seenBrainDirs = new Set();

  for (const appDir of appDirsByKey.values()) {
    if (Date.now() >= deadlineMs) {
      partial = true;
      break;
    }

    const convDir = path.join(appDir, "conversations");
    const convKey = toComparePath(await canonicalizeExistingPath(convDir));
    if (!seenConvDirs.has(convKey)) {
      seenConvDirs.add(convKey);
      try {
        const entries = await fs.readdir(convDir, { withFileTypes: true });
        const fileEntries = entries.filter((ent) => ent.isFile());
        const hitCap = await runBoundedPool(
          fileEntries,
          STORAGE_STAT_CONCURRENCY,
          deadlineMs,
          async (ent) => {
            try {
              const st = await fs.stat(path.join(convDir, ent.name));
              conversationDbBytes += st.size;
              if (/\.(?:db|pb)$/i.test(ent.name)) {
                conversationDbFiles += 1;
              }
            } catch {
              // Ignore transient/vanished files
            }
          },
        );
        if (hitCap) partial = true;
      } catch {
        // Directory not present
      }
    }

    if (Date.now() >= deadlineMs) {
      partial = true;
      break;
    }

    const brainDir = path.join(appDir, "brain");
    const brainKey = toComparePath(await canonicalizeExistingPath(brainDir));
    if (!seenBrainDirs.has(brainKey)) {
      seenBrainDirs.add(brainKey);
      try {
        const entries = await fs.readdir(brainDir, { withFileTypes: true });
        const dirEntries = entries.filter((ent) => ent.isDirectory());
        const hitCap = await runBoundedPool(
          dirEntries,
          STORAGE_STAT_CONCURRENCY,
          deadlineMs,
          async (ent) => {
            const sessDir = path.join(brainDir, ent.name);
            let latestMtime = 0;
            try {
              const dirSt = await fs.stat(sessDir);
              latestMtime = dirSt.mtimeMs;
              brainSessionDirs += 1;
            } catch {
              return;
            }
            for (const logName of ["transcript.jsonl", "transcript_full.jsonl"]) {
              try {
                const st = await fs.stat(
                  path.join(sessDir, ".system_generated", "logs", logName),
                );
                transcriptBytes += st.size;
                if (st.mtimeMs > latestMtime) latestMtime = st.mtimeMs;
              } catch {
                // Optional log file
              }
            }
            if (latestMtime > 0 && latestMtime < staleCutoffMs) {
              staleSessions60d += 1;
            }
          },
        );
        if (hitCap) partial = true;
      } catch {
        // Directory not present
      }
    }
  }

  return {
    totalTrackedBytes: conversationDbBytes + transcriptBytes,
    conversationDbBytes,
    conversationDbFiles,
    transcriptBytes,
    brainSessionDirs,
    staleSessions60d,
    partial,
  };
}

async function inspectHostContextHygiene(workspaceDir = process.cwd()) {
  const deadlineMs = Date.now() + HOST_HYGIENE_SCAN_BUDGET_MS;
  const home = getHomeDir();
  const geminiRoot = process.env.GEMINI_HOME?.trim()
    ? path.resolve(expandHomePath(process.env.GEMINI_HOME.trim()))
    : path.join(home, ".gemini");

  // 1. Check workspace & global rule files against Antigravity 24,000 B cap
  //    (verified on Desktop v2.34-v2.36 / CLI v1.5.x, rules.go:736)
  const ruleCandidates = [];
  const resolvedWs = workspaceDir ? path.resolve(workspaceDir) : "";
  const isWsHome =
    !resolvedWs ||
    toComparePath(await canonicalizeExistingPath(resolvedWs)) ===
      toComparePath(await canonicalizeExistingPath(home));
  if (resolvedWs && !isWsHome) {
    for (const rel of ["AGENTS.md", "GEMINI.md", "CLAUDE.md"]) {
      ruleCandidates.push({ label: rel, filePath: path.join(resolvedWs, rel) });
    }
    for (const relDir of [
      path.join(".agent", "rules"),
      path.join(".agents", "rules"),
      path.join(".gemini", "rules"),
    ]) {
      if (Date.now() >= deadlineMs) break;
      try {
        const entries = await fs.readdir(path.join(resolvedWs, relDir), {
          withFileTypes: true,
        });
        for (const ent of entries
          .filter((e) => e.isFile() && /\.md$/i.test(e.name))
          .slice(0, 16)) {
          ruleCandidates.push({
            label: `${relDir.replace(/\\/g, "/")}/${ent.name}`,
            filePath: path.join(resolvedWs, relDir, ent.name),
          });
        }
      } catch {
        // Optional rules dir
      }
    }
  }
  for (const globalName of ["AGENTS.md", "GEMINI.md"]) {
    ruleCandidates.push({
      label: `~/.gemini/${globalName}`,
      filePath: path.join(geminiRoot, globalName),
    });
  }

  const oversizedRules = [];
  const nearCapRules = [];
  const seenRulePaths = new Set();
  for (const cand of ruleCandidates) {
    if (Date.now() >= deadlineMs) break;
    const key = toComparePath(await canonicalizeExistingPath(cand.filePath));
    if (seenRulePaths.has(key)) continue;
    seenRulePaths.add(key);
    try {
      const st = await fs.stat(cand.filePath);
      if (!st.isFile()) continue;
      if (st.size > ANTIGRAVITY_RULE_CAP_BYTES) {
        oversizedRules.push({
          label: cand.label,
          bytes: st.size,
          truncatedBytes: st.size - ANTIGRAVITY_RULE_CAP_BYTES,
        });
      } else if (st.size >= ANTIGRAVITY_RULE_NEAR_CAP_BYTES) {
        nearCapRules.push({ label: cand.label, bytes: st.size });
      }
    } catch {
      // File absent
    }
  }
  oversizedRules.sort((a, b) => b.bytes - a.bytes);
  nearCapRules.sort((a, b) => b.bytes - a.bytes);

  // 2. Inspect MCP schema directories on Desktop & CLI and flag disabled-plugin residues
  const hostCfg =
    (await readJsonSafe(path.join(geminiRoot, "config", "config.json"))) || {};
  const disabledPlugins = new Set();
  if (hostCfg.plugins && typeof hostCfg.plugins === "object") {
    for (const [pluginId, meta] of Object.entries(hostCfg.plugins)) {
      if (meta && typeof meta === "object" && meta.enabled === false) {
        disabledPlugins.add(pluginId.toLowerCase());
      }
    }
  }

  const mcpSurfaces = [];
  const staleDisabledMcp = [];
  for (const surface of [
    { label: "Desktop", dir: path.join(geminiRoot, "antigravity", "mcp") },
    { label: "CLI", dir: path.join(geminiRoot, "antigravity-cli", "mcp") },
  ]) {
    if (Date.now() >= deadlineMs) break;
    try {
      const serverEntries = await fs.readdir(surface.dir, { withFileTypes: true });
      let serverCount = 0;
      let totalBytes = 0;
      for (const srv of serverEntries) {
        if (!srv.isDirectory()) continue;
        serverCount += 1;
        let srvBytes = 0;
        let srvFiles = 0;
        try {
          const files = await fs.readdir(path.join(surface.dir, srv.name), {
            withFileTypes: true,
          });
          for (const f of files) {
            if (!f.isFile()) continue;
            const st = await fs.stat(path.join(surface.dir, srv.name, f.name)).catch(() => null);
            if (st) {
              srvBytes += st.size;
              srvFiles += 1;
            }
          }
        } catch {
          // Ignore unreadable server dir
        }
        totalBytes += srvBytes;
        const lowerSrv = srv.name.toLowerCase();
        for (const disabledId of disabledPlugins) {
          if (
            srvBytes > 0 &&
            (lowerSrv === disabledId || lowerSrv.startsWith(`${disabledId}_`))
          ) {
            staleDisabledMcp.push({
              surface: surface.label,
              serverDir: srv.name,
              pluginId: disabledId,
              bytes: srvBytes,
              files: srvFiles,
            });
            break;
          }
        }
      }
      if (serverCount > 0 || totalBytes > 0) {
        mcpSurfaces.push({ label: surface.label, serverCount, totalBytes });
      }
    } catch {
      // Surface mcp dir absent
    }
  }

  return {
    ruleCapBytes: ANTIGRAVITY_RULE_CAP_BYTES,
    oversizedRules,
    nearCapRules,
    mcpSurfaces,
    staleDisabledMcp,
  };
}

async function runDoctor(targetDir, quiet = false, doctorOpts = {}) {
  const nodeVer = checkNodeVersion();
  const hasRg = hasCommand("rg", ["--version"]);
  const hasAgy = hasCommand("agy", ["--version"]);
  const exists = await pathExists(targetDir);

  const report = {
    nodeVersion: nodeVer,
    ripgrep: hasRg,
    agyCli: hasAgy,
    targetDir,
    installed: exists,
    mcpTools: [],
    hookLatencyMs: null,
    hookBytes: null,
    agyValidated: null,
    localStorage: null,
    hostHygiene: null,
  };

  if (!exists) {
    if (!quiet) {
      console.log(`agy-fast is not installed at: ${targetDir}`);
    }
    return { ok: false, report };
  }

  const mcpPath = path.join(targetDir, "dist", "mcp-server.mjs");
  const hookPath = path.join(targetDir, "dist", "session-start.mjs");
  const mcpCheck = await verifyMcpServerLive(mcpPath);
  const hookCheck = await verifySessionStartLive(hookPath, targetDir);

  report.mcpTools = mcpCheck.tools;
  report.hookLatencyMs = hookCheck.durationMs;
  report.hookBytes = hookCheck.bytes;

  if (hasAgy) {
    const valRes = spawnCliSync("agy", ["plugin", "validate", "--strict", targetDir], {
      encoding: "utf8",
      timeout: 10_000,
    });
    report.agyValidated = !valRes.error && valRes.status === 0;
    report.agyValidateOutput = [valRes.error?.message, valRes.stdout, valRes.stderr]
      .filter((s) => typeof s === "string" && s.trim())
      .join("\n")
      .trim();
  }

  const manifest = await readJsonSafe(path.join(targetDir, "plugin.json"));
  const installedVersion =
    manifest && typeof manifest.version === "string" ? manifest.version : "unknown";
  const cacheDir = getUpdaterCacheDir();
  const statePath = await getUpdaterStatePath(targetDir);
  const updaterCfg = (await readJsonSafe(path.join(cacheDir, "config.json"))) || {};
  const updaterState = (await readJsonSafe(statePath)) || {};
  const effectiveAutoMode =
    process.env.AGY_FAST_AUTO_UPDATE?.trim().toLowerCase() ||
    updaterCfg.autoUpdate ||
    "notify";
  const effectiveInterval =
    process.env.AGY_FAST_UPDATE_INTERVAL_HOURS?.trim() ||
    updaterCfg.checkIntervalHours ||
    4;
  const effectiveChannel =
    process.env.AGY_FAST_UPDATE_CHANNEL?.trim().toLowerCase() ||
    updaterCfg.channel ||
    "release";
  const rawEnvEditsFormat = process.env.AGY_FAST_EDITS_FORMAT?.trim().toLowerCase() || "";
  const validEnvEditsFormat = ["auto", "array", "string"].includes(rawEnvEditsFormat)
    ? rawEnvEditsFormat
    : "";
  const validCfgEditsFormat =
    typeof updaterCfg.editsFormat === "string" &&
    ["auto", "array", "string"].includes(updaterCfg.editsFormat.trim().toLowerCase())
      ? updaterCfg.editsFormat.trim().toLowerCase()
      : "";
  const effectiveEditsFormat = validEnvEditsFormat || validCfgEditsFormat || "auto";
  const effectiveToolLoading =
    parseToolLoadingValue(process.env.AGY_FAST_TOOL_LOADING || "") ||
    parseToolLoadingValue(updaterCfg.toolLoading) ||
    "eager";
  const installedMcpCfg = await readJsonSafe(path.join(targetDir, "mcp_config.json"));
  const installedToolsMap =
    installedMcpCfg?.mcpServers?.fast?.tools &&
    typeof installedMcpCfg.mcpServers.fast.tools === "object"
      ? installedMcpCfg.mcpServers.fast.tools
      : {};
  const eagerToolCount = EXPECTED_MCP_TOOLS.filter(
    (t) => installedToolsMap?.[t]?.eager === true,
  ).length;
  const rawHostOverride = process.env.AGY_FAST_HOST?.trim() || "";
  const validHostOverride =
    /^(?:cli|desktop|app|antigravity|ide|unknown)(?:[@\-/\s]v?\d+\.\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)?$/i.test(
      rawHostOverride,
    )
      ? rawHostOverride
      : "";
  const hostEnvLabel =
    validHostOverride || process.env.ANTIGRAVITY_LS_VERSION?.trim() || "auto";

  const isolatedProfiles = doctorOpts.checkIsolated
    ? await Promise.all(
        (await discoverIsolatedPluginDirs(targetDir)).map((iso) =>
          inspectIsolatedPluginDir(iso),
        ),
      )
    : [];
  report.isolatedProfiles = isolatedProfiles;
  report.localStorage = doctorOpts.checkStorage
    ? await inspectLocalAntigravityStorage()
    : null;
  report.hostHygiene = doctorOpts.checkHygiene
    ? await inspectHostContextHygiene(doctorOpts.workspaceDir || process.cwd())
    : null;

  const binShims = doctorOpts.skipBinShims
    ? []
    : await collectBinShimStatuses(targetDir, doctorOpts.binShimDir || "");
  report.binShims = binShims;

  const missingTools = EXPECTED_MCP_TOOLS.filter((t) => !mcpCheck.tools.includes(t));
  const hasAllExpectedTools = missingTools.length === 0;
  const hasLocalRules =
    report.agyValidated === false ? await hasLocalRuleFiles(targetDir) : false;

  if (!quiet) {
    console.log("agy-fast health check:");
    console.log(`  - Plugin path : ${targetDir}`);
    console.log(`  - Version     : v${installedVersion}`);
    console.log(`  - Node.js     : v${nodeVer} (OK)`);
    console.log(
      `  - ripgrep (rg): ${hasRg ? "available (fast search active)" : "not found (automatic Node.js fallback active)"}`,
    );
    console.log(
      `  - MCP server  : ${
        hasAllExpectedTools
          ? `OK (${mcpCheck.tools.length} tools: ${mcpCheck.tools.join(", ")})`
          : `FAILED (missing: ${missingTools.join(", ")}; found: ${mcpCheck.tools.join(", ") || "none"})`
      }`,
    );
    console.log(
      `  - Tool loading: ${effectiveToolLoading} (${eagerToolCount}/${EXPECTED_MCP_TOOLS.length} tools eager in mcp_config.json)`,
    );
    console.log(
      `  - Host compat : editsFormat=${effectiveEditsFormat} (active edits schema: ${mcpCheck.applyEditsSchemaType}; host=${hostEnvLabel})`,
    );
    console.log(
      `  - SessionStart: ${hookCheck.bytes > 0 ? "OK" : "EMPTY (FAILED)"} (${hookCheck.durationMs}ms, ${hookCheck.bytes} bytes)`,
    );
    const availCmp = updaterState.availableVersion
      ? compareSemverSimple(updaterState.availableVersion, installedVersion)
      : null;
    const hasFreshSemverUpdate =
      Boolean(updaterState.availableVersion) && (availCmp === null || availCmp > 0);
    const skipCmp = updaterState.skippedVersion
      ? compareSemverSimple(updaterState.skippedVersion, installedVersion)
      : null;
    const hasActiveSkip =
      Boolean(updaterState.skippedVersion) && (skipCmp === null || skipCmp > 0);
    const hasMainUpdate =
      !updaterState.availableVersion &&
      Boolean(updaterState.availableCommit) &&
      updaterState.availableCommit !== updaterState.lastAppliedCommit;

    const checkParts = [];
    if (
      hasFreshSemverUpdate &&
      (!hasActiveSkip || updaterState.availableVersion !== updaterState.skippedVersion)
    ) {
      checkParts.push(`update available: v${updaterState.availableVersion}`);
    } else if (hasMainUpdate) {
      checkParts.push(
        `update available: ${updaterState.availableRef || "main"} (${String(updaterState.availableCommit).slice(0, 7)})`,
      );
    } else if (hasActiveSkip) {
      checkParts.push(`skipped: v${updaterState.skippedVersion}`);
    }
    if (updaterState.lastCheckAt) {
      checkParts.push(`last check: ${updaterState.lastCheckAt}`);
    } else if (checkParts.length === 0) {
      checkParts.push("not checked yet");
    }
    if (updaterState.lastError) {
      const compactErr = String(updaterState.lastError).replace(/\s+/g, " ").trim().slice(0, 120);
      checkParts.push(`last error: ${compactErr}`);
    }
    console.log(
      `  - Auto-update : ${effectiveAutoMode} (interval: ${effectiveInterval}h, channel: ${effectiveChannel}; ${checkParts.join("; ")})`,
    );
    if (
      (hasFreshSemverUpdate || hasMainUpdate) &&
      (!hasActiveSkip || updaterState.availableVersion !== updaterState.skippedVersion) &&
      updaterState.availableReleaseUrl
    ) {
      console.log(`      Release: ${updaterState.availableReleaseUrl}`);
    }
    if (hasAgy) {
      console.log(
        `  - agy validate: ${report.agyValidated ? "PASSED (--strict)" : "FAILED"}`,
      );
      if (!report.agyValidated && report.agyValidateOutput) {
        for (const line of report.agyValidateOutput.split(/\r?\n/).slice(0, 12)) {
          if (line.trim()) console.log(`      ${line.trim()}`);
        }
      }
      if (!report.agyValidated && hasLocalRules) {
        console.log(
          "      Hint: custom rules/*.local.md files require YAML frontmatter (`---\\ntrigger: always_on\\n---`) for Antigravity to load and validate them.",
        );
      }
    }
    for (const iso of isolatedProfiles) {
      const desc =
        iso.status === "ok"
          ? iso.mode === "symlink"
            ? `OK (linked -> ${iso.linkTarget})`
            : `OK (installed v${iso.version || "unknown"})`
          : iso.status === "disabled"
            ? "DISABLED in profile config.json"
            : iso.status === "broken"
              ? `BROKEN (${iso.pluginDir})`
              : `MISSING (${iso.pluginDir} — run 'install' to sync)`;
      console.log(`  - ${iso.label}: ${desc}`);
    }
    for (const shimDirReport of binShims) {
      if (shimDirReport.status === "none") {
        const foreignNote =
          shimDirReport.foreign.length > 0
            ? ` (non-agy-fast present: ${shimDirReport.foreign.map((f) => f.fileName).join(", ")})`
            : "";
        console.log(`  - Bin shims   : none in ${shimDirReport.binDir}${foreignNote}`);
        continue;
      }
      if (shimDirReport.status === "broken") {
        const brokenNames = shimDirReport.broken.map((e) => e.fileName).join(", ");
        const okPart =
          shimDirReport.okEntries.length > 0
            ? `; OK: ${shimDirReport.okEntries.map((e) => e.fileName).join(", ")}`
            : "";
        console.log(
          `  - Bin shims   : BROKEN (${brokenNames} in ${shimDirReport.binDir}${okPart})`,
        );
        continue;
      }
      const okNames = shimDirReport.okEntries.map((e) => e.fileName).join(", ");
      const targetSuffix =
        shimDirReport.otherTargets.length > 0
          ? ` -> ${shimDirReport.otherTargets.join(", ")}`
          : "";
      const foreignSuffix =
        shimDirReport.foreign.length > 0
          ? `; non-agy-fast skipped: ${shimDirReport.foreign.map((f) => f.fileName).join(", ")}`
          : "";
      console.log(
        `  - Bin shims   : OK (${okNames} in ${shimDirReport.binDir}${targetSuffix}${foreignSuffix})`,
      );
    }
    const stg = report.localStorage;
    if (stg && (stg.totalTrackedBytes > 0 || stg.brainSessionDirs > 0)) {
      const staleNote =
        stg.staleSessions60d > 0
          ? `; ${stg.staleSessions60d} session(s) older than ${STORAGE_STALE_DAYS}d`
          : "";
      const partialNote = stg.partial ? "; partial scan (time budget reached)" : "";
      console.log(
        `  - Storage     : ${formatByteSize(stg.totalTrackedBytes)} tracked (conversations: ${formatByteSize(stg.conversationDbBytes)} / ${stg.conversationDbFiles} DBs, transcripts: ${formatByteSize(stg.transcriptBytes)} / ${stg.brainSessionDirs} brain dirs${staleNote}${partialNote})`,
      );
      if (stg.totalTrackedBytes >= STORAGE_WARN_BYTES || stg.staleSessions60d >= 50) {
        console.log(
          "      Tip: archive or prune old local Antigravity conversations/brain sessions (e.g. ~/.gemini/antigravity* or custom GEMINI_HOME) periodically to keep disk & benchmark scans lean (read-only notice; agy-fast never deletes your history).",
        );
      }
    }
    const hyg = report.hostHygiene;
    if (hyg) {
      if (hyg.oversizedRules.length > 0) {
        const items = hyg.oversizedRules
          .slice(0, 4)
          .map(
            (r) =>
              `${r.label} (${formatByteSize(r.bytes)}, -${formatByteSize(r.truncatedBytes)} truncated)`,
          )
          .join("; ");
        console.log(
          `  - Rule cap    : WARNING (>24,000 B silent truncation on Antigravity Desktop v2.34-v2.36 / CLI v1.5.x): ${items}`,
        );
        console.log(
          "      Tip: keep rule files <=24,000 B or split detail into on-demand skills/docs so rules.go does not silently drop tail rules.",
        );
      } else if (hyg.nearCapRules.length > 0) {
        const items = hyg.nearCapRules
          .slice(0, 4)
          .map((r) => `${r.label} (${formatByteSize(r.bytes)})`)
          .join("; ");
        console.log(
          `  - Rule cap    : NEAR 24,000 B cap (Desktop v2.34-v2.36 / CLI v1.5.x): ${items}`,
        );
      }
      if (hyg.mcpSurfaces.length > 0 || hyg.staleDisabledMcp.length > 0) {
        const surfText = hyg.mcpSurfaces
          .map((s) => `${s.label}: ${s.serverCount} server(s), ${formatByteSize(s.totalBytes)}`)
          .join(" | ");
        console.log(`  - MCP schemas : ${surfText || "none"}`);
        if (hyg.staleDisabledMcp.length > 0) {
          const staleText = hyg.staleDisabledMcp
            .slice(0, 4)
            .map((s) => `${s.surface}/${s.serverDir} (${formatByteSize(s.bytes)}, disabled plugin '${s.pluginId}')`)
            .join("; ");
          console.log(`      Notice: disabled plugin MCP schema residue found: ${staleText}`);
        }
      }
    }
  }

  const hasBrokenIsolated = isolatedProfiles.some((iso) => iso.status === "broken");
  const hasBrokenBinShims =
    Boolean(doctorOpts.checkBinShims) &&
    binShims.some((b) => b.status === "broken");
  const ok =
    hasAllExpectedTools &&
    hookCheck.bytes > 0 &&
    !hasBrokenIsolated &&
    !hasBrokenBinShims &&
    (report.agyValidated === null || report.agyValidated === true);
  return { ok, report };
}

async function runInstall(opts) {
  checkNodeVersion();

  const resolvedSrc = await fs.realpath(REPO_ROOT);
  const resolvedDst = path.resolve(opts.targetDir);
  const dstStat = await lstatSafe(resolvedDst);

  let sameDirectory = false;
  if (dstStat && !dstStat.isSymbolicLink()) {
    const srcCompare = toComparePath(resolvedSrc);
    const dstCompare = toComparePath(await fs.realpath(resolvedDst));
    sameDirectory = srcCompare === dstCompare;
    if (isStrictAncestorPath(dstCompare, srcCompare)) {
      throw new Error(
        `Refusing to install into ${resolvedDst}: target is an ancestor directory of ${resolvedSrc}.`,
      );
    }
  }

  await assertSourceFilesPresent(resolvedSrc);
  const effectiveToolLoading = await resolveEffectiveToolLoading(opts.toolLoading);
  const installOpts = { ...opts, effectiveToolLoading };

  if (sameDirectory) {
    if (!opts.quiet) {
      console.log(`Repository is already at target plugin directory: ${resolvedDst}`);
    }
  } else if (opts.useLink) {
    await assertRemovableTarget(resolvedDst, dstStat);
    const { preserved: replacedLocalRules } = await snapshotLocalRuleFiles(resolvedDst);
    await fs.mkdir(path.dirname(resolvedDst), { recursive: true });
    try {
      await removeTargetPath(resolvedDst, dstStat, { quiet: opts.quiet });
    } catch (err) {
      if (isLockedTargetError(err)) {
        throw formatLockedTargetError(resolvedDst, err);
      }
      throw err;
    }
    const linkType = process.platform === "win32" ? "junction" : "dir";
    await fs.symlink(resolvedSrc, resolvedDst, linkType);
    if (!opts.quiet) {
      console.log(`Linked ${resolvedDst} -> ${resolvedSrc}`);
      if (replacedLocalRules.length > 0) {
        console.log(
          `Note: --link replaced ${resolvedDst}; local rule file(s) were not copied into dev checkout: ${replacedLocalRules.map((f) => `rules/${f.name}`).join(", ")}`,
        );
      }
    }
  } else {
    // Preserve clean target directory and any user-authored rules/*.local.md when re-installing / upgrading
    await assertRemovableTarget(resolvedDst, dstStat);
    const { preserved: preservedLocalRules, skipped: skippedLocalRules } =
      await snapshotLocalRuleFiles(resolvedDst);
    let inPlaceSynced = false;
    if (dstStat) {
      try {
        await removeTargetPath(resolvedDst, dstStat, { quiet: opts.quiet });
      } catch (err) {
        if (dstStat.isDirectory() && !dstStat.isSymbolicLink() && isLockedTargetError(err)) {
          try {
            await syncRuntimeFilesAtomically(resolvedSrc, resolvedDst);
          } catch (syncErr) {
            if (isLockedTargetError(syncErr)) {
              throw formatLockedTargetError(resolvedDst, syncErr);
            }
            throw syncErr;
          }
          inPlaceSynced = true;
        } else if (isLockedTargetError(err)) {
          throw formatLockedTargetError(resolvedDst, err);
        } else {
          throw err;
        }
      }
    }
    if (!inPlaceSynced) {
      await copyRuntimeFiles(resolvedSrc, resolvedDst);
    }
    await applyToolLoadingToCopiedPluginDir(resolvedDst, effectiveToolLoading);
    const { restored } = await restoreLocalRuleFiles(resolvedDst, preservedLocalRules);
    if (!opts.quiet) {
      console.log(`Installed agy-fast to ${resolvedDst}`);
      if (inPlaceSynced) {
        console.log(
          `Note: ${resolvedDst} was locked by a running process; updated files atomically in-place. Reload your host window to load the new MCP server.`,
        );
      }
      if (effectiveToolLoading === "lazy") {
        console.log("Applied MCP tool loading mode: lazy (all 5 tools via call_mcp_tool).");
      }
      if (restored.length > 0) {
        console.log(
          `Preserved local rule file(s): ${restored.map((n) => `rules/${n}`).join(", ")}`,
        );
      }
      if (skippedLocalRules.length > 0) {
        console.log(
          `Skipped unsafe/oversized local rule file(s): ${skippedLocalRules.map((s) => `rules/${s.name} (${s.reason})`).join(", ")}`,
        );
      }
    }
  }

  const hasAgy = hasCommand("agy", ["--version"]);
  const isGlobalTarget = !opts.isProject && !opts.isCustomTarget;
  const syncIsolated = isGlobalTarget && !opts.skipAcp;
  const isolatedTargets = syncIsolated ? await discoverIsolatedPluginDirs(resolvedDst) : [];
  for (const isolated of isolatedTargets) {
    await syncIsolatedPluginDir(resolvedSrc, resolvedDst, isolated, installOpts);
  }

  if (hasAgy && !opts.skipEnable && isGlobalTarget) {
    const enableRes = spawnCliSync("agy", ["plugin", "enable", PLUGIN_NAME], {
      encoding: "utf8",
      timeout: 10_000,
    });
    if (!opts.quiet) {
      if (!enableRes.error && enableRes.status === 0) {
        console.log(`Enabled plugin '${PLUGIN_NAME}' via agy CLI.`);
      } else {
        console.log(
          `Note: could not auto-enable via 'agy plugin enable ${PLUGIN_NAME}'. Enable it in Antigravity Customizations UI.`,
        );
      }
    }
  }

  if (
    opts.autoUpdate ||
    opts.intervalHours !== null ||
    opts.channel ||
    opts.repoUrl ||
    opts.editsFormat ||
    opts.toolLoading
  ) {
    const patch = {};
    if (opts.autoUpdate) patch.autoUpdate = opts.autoUpdate;
    if (opts.intervalHours !== null) patch.checkIntervalHours = opts.intervalHours;
    if (opts.channel) patch.channel = opts.channel;
    if (opts.repoUrl) patch.repoUrl = opts.repoUrl;
    if (opts.editsFormat) patch.editsFormat = opts.editsFormat;
    if (opts.toolLoading) patch.toolLoading = opts.toolLoading;
    await writeUpdaterConfigFile(patch);
  }

  let shimInstallRes = null;
  if (opts.binShim || opts.binShimDir) {
    shimInstallRes = await installBinShims(resolvedDst, opts);
  }

  const checkBinShims = Boolean(shimInstallRes?.attempted);
  const { ok } = await runDoctor(resolvedDst, opts.quiet, {
    checkIsolated: syncIsolated,
    binShimDir: opts.binShimDir,
    checkBinShims,
    skipBinShims: Boolean(opts.isProject && !opts.binShimDir),
  });
  if (!ok) {
    throw new Error("Post-install health check failed.");
  }

  if (!opts.quiet) {
    console.log("");
    console.log("Installation complete. Next steps:");
    console.log("  - Antigravity CLI (agy)    : Start a new session to activate agy-fast.");
    console.log("  - Antigravity Desktop / IDE: Open Customizations -> Installed and ensure 'agy-fast' is enabled.");
    if (isolatedTargets.length > 0) {
      console.log(
        `  - T3 Code / ACP (${isolatedTargets.length})        : Start a new thread (or reload provider) to activate agy-fast.`,
      );
    }
  }
}

async function runConfig(opts) {
  const patch = {};
  if (opts.autoUpdate) patch.autoUpdate = opts.autoUpdate;
  if (opts.intervalHours !== null) patch.checkIntervalHours = opts.intervalHours;
  if (opts.channel) patch.channel = opts.channel;
  if (opts.repoUrl) patch.repoUrl = opts.repoUrl;
  if (opts.editsFormat) patch.editsFormat = opts.editsFormat;
  if (opts.toolLoading) patch.toolLoading = opts.toolLoading;

  let cfgPath = path.join(getUpdaterCacheDir(), "config.json");
  let cfg;
  if (Object.keys(patch).length > 0) {
    const res = await writeUpdaterConfigFile(patch);
    cfgPath = res.cfgPath;
    cfg = res.config;
  } else {
    cfg = (await readJsonSafe(cfgPath)) || {};
  }

  let appliedToolLoadingNote = "";
  if (opts.toolLoading) {
    const resolvedDst = path.resolve(opts.targetDir);
    const applyRes = await applyToolLoadingToCopiedPluginDir(resolvedDst, opts.toolLoading);
    if (applyRes.applied) {
      const isGlobalTarget = !opts.isProject && !opts.isCustomTarget;
      if (isGlobalTarget && !opts.skipAcp) {
        const isolatedTargets = await discoverIsolatedPluginDirs(resolvedDst);
        for (const iso of isolatedTargets) {
          await applyToolLoadingToCopiedPluginDir(iso.pluginDir, opts.toolLoading);
        }
      }
      appliedToolLoadingNote = `Applied '${opts.toolLoading}' mode to ${path.join(resolvedDst, "mcp_config.json")} (start a new session to take effect).`;
    } else if (applyRes.reason === "symlink" || applyRes.reason === "git-clone") {
      appliedToolLoadingNote = `Saved toolLoading='${opts.toolLoading}' in config.json (skipped rewriting ${resolvedDst}/mcp_config.json because it is a ${applyRes.reason}; edit manually or reinstall as a copied install).`;
    }
  }

  if (!opts.quiet) {
    console.log(`agy-fast updater config (${cfgPath}):`);
    console.log(`  - autoUpdate        : ${cfg.autoUpdate || "notify"}`);
    console.log(`  - checkIntervalHours: ${cfg.checkIntervalHours || 4}`);
    console.log(`  - channel           : ${cfg.channel || "release"}`);
    console.log(`  - repoUrl           : ${cfg.repoUrl || "https://github.com/INK-Q/agy-fast.git"}`);
    console.log(`  - editsFormat       : ${cfg.editsFormat || "auto"}`);
    console.log(`  - toolLoading       : ${cfg.toolLoading || "eager"}`);
    if (appliedToolLoadingNote) {
      console.log(`  ${appliedToolLoadingNote}`);
    }
  }
}

function invokeUpdaterJson(updaterPath, args) {
  const res = spawnSync(process.execPath, [updaterPath, ...args, "--json"], {
    encoding: "utf8",
    timeout: 60_000,
    windowsHide: true,
  });
  let parsed = null;
  try {
    parsed = JSON.parse((res.stdout || "").trim());
  } catch {
    // Non-JSON error output handled below
  }
  if (!parsed) {
    const detail = (res.stderr || res.stdout || res.error?.message || "updater failed").trim();
    throw new Error(detail);
  }
  return parsed;
}

async function promptUpdateDecision(question) {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  try {
    const raw = await rl.question(question);
    const ans = raw.trim().toLowerCase();
    if (ans === "y" || ans === "yes") return "yes";
    if (ans === "s" || ans === "skip") return "skip";
    return "no";
  } catch {
    return "no";
  } finally {
    rl.close();
  }
}

async function runUpdate(opts) {
  checkNodeVersion();
  const resolvedDst = path.resolve(opts.targetDir);
  if (!(await pathExists(resolvedDst))) {
    throw new Error(
      `agy-fast is not installed at ${resolvedDst}. Run 'install' first.`,
    );
  }

  if (opts.autoUpdate || opts.intervalHours !== null || opts.editsFormat || opts.toolLoading) {
    const patch = {};
    if (opts.autoUpdate) patch.autoUpdate = opts.autoUpdate;
    if (opts.intervalHours !== null) patch.checkIntervalHours = opts.intervalHours;
    if (opts.editsFormat) patch.editsFormat = opts.editsFormat;
    if (opts.toolLoading) patch.toolLoading = opts.toolLoading;
    await writeUpdaterConfigFile(patch);
  }

  // Prefer the updater paired with this install.mjs so new CLI flags (e.g. --skip-version)
  // are never sent to an older installed dist/updater.mjs that might ignore unknown flags.
  const repoUpdater = path.join(REPO_ROOT, "dist", "updater.mjs");
  const installedUpdater = path.join(resolvedDst, "dist", "updater.mjs");
  const updaterPath = (await pathExists(repoUpdater))
    ? repoUpdater
    : installedUpdater;
  if (!(await pathExists(updaterPath))) {
    throw new Error("Missing dist/updater.mjs. Run 'npm run build' or reinstall agy-fast.");
  }

  const runSkipCommand = (rawVer) => {
    const lower = rawVer.toLowerCase();
    const isClear = lower === "none" || lower === "clear";
    const expectedStatus = isClear ? "cleared-skip" : "skipped-version";
    const skipArgs = isClear
      ? ["--plugin-dir", resolvedDst, "--clear-skip"]
      : ["--plugin-dir", resolvedDst, "--skip-version", rawVer];
    const skipParsed = invokeUpdaterJson(updaterPath, skipArgs);
    if (skipParsed.status === "error") {
      throw new Error(skipParsed.error || skipParsed.message || "Failed to update skip preference.");
    }
    if (skipParsed.status !== expectedStatus) {
      throw new Error(
        `Updater at ${updaterPath} does not support --skip-version (returned status: '${skipParsed.status}').`,
      );
    }
    if (!opts.quiet) {
      console.log(skipParsed.message);
    }
  };

  if (opts.skipVersion) {
    runSkipCommand(opts.skipVersion);
    return;
  }

  const baseArgs = ["--plugin-dir", resolvedDst];
  if (opts.channel) baseArgs.push("--channel", opts.channel);
  if (opts.repoUrl) baseArgs.push("--repo", opts.repoUrl);

  const installerScriptPath = path.join(resolvedDst, "scripts", "install.mjs");
  let parsed = null;

  if (opts.promptUpdate && !opts.checkOnly) {
    const checkArgs = [...baseArgs, "--check"];
    if (opts.force) checkArgs.push("--force");
    const checkParsed = invokeUpdaterJson(updaterPath, checkArgs);
    if (checkParsed.status === "error") {
      if (!opts.quiet) console.log(checkParsed.message);
      throw new Error(checkParsed.error || checkParsed.message);
    }
    if (checkParsed.status !== "available") {
      // Reuse checkParsed without returning early so --tool-loading and isolated ACP sync still run on up-to-date
      parsed = checkParsed;
    } else {
      if (!opts.quiet) {
        console.log(checkParsed.message);
        if (checkParsed.commitSha) {
          console.log(`Commit       : ${checkParsed.commitSha.slice(0, 12)}`);
        }
        if (checkParsed.compareUrl) {
          console.log(`Compare diff : ${checkParsed.compareUrl}`);
        }
        if (checkParsed.releaseUrl) {
          console.log(`Release notes: ${checkParsed.releaseUrl}`);
        }
        if (checkParsed.publishedAt) {
          console.log(`Published at : ${checkParsed.publishedAt}`);
        }
      }

      const targetLabel = checkParsed.latestVersion
        ? `v${checkParsed.currentVersion} -> v${checkParsed.latestVersion}`
        : `branch '${checkParsed.latestRef || "main"}'`;
      const isManagedUpdate =
        checkParsed.installKind === "copied" || checkParsed.installKind === "git-clone";
      const question = isManagedUpdate
        ? `Update agy-fast ${targetLabel} now? [y]es / [n]o / [s]kip this version (default: n): `
        : `This install (${checkParsed.installKind}) requires manual git pull/build. Skip notifications for ${targetLabel}? [s]kip / [n]o (default: n): `;

      const decision = await promptUpdateDecision(question);
      if (decision === "skip") {
        if (checkParsed.latestVersion) {
          runSkipCommand(checkParsed.latestVersion);
        } else if (!opts.quiet) {
          console.log("Skipped for now (no semver version tag to persist).");
        }
        return;
      }
      if (decision !== "yes" || !isManagedUpdate) {
        if (!opts.quiet) {
          console.log(
            isManagedUpdate
              ? `Update declined. Run \`node "${installerScriptPath}" update\` whenever you are ready.`
              : "No changes made.",
          );
        }
        return;
      }
    }
  }

  if (!parsed) {
    const updaterArgs = [...baseArgs];
    if (opts.checkOnly) updaterArgs.push("--check");
    if (opts.force) updaterArgs.push("--force");
    parsed = invokeUpdaterJson(updaterPath, updaterArgs);
  }
  if (opts.toolLoading && !opts.checkOnly) {
    await applyToolLoadingToCopiedPluginDir(resolvedDst, opts.toolLoading);
  }

  if (!opts.quiet) {
    console.log(parsed.message);
    if (opts.checkOnly && parsed.status === "available") {
      if (parsed.commitSha) {
        console.log(`Commit       : ${parsed.commitSha.slice(0, 12)}`);
      }
      if (parsed.compareUrl) {
        console.log(`Compare diff : ${parsed.compareUrl}`);
      }
      if (parsed.releaseUrl) {
        console.log(`Release notes: ${parsed.releaseUrl}`);
      }
      console.log(`  - Update now : node "${installerScriptPath}" update`);
      if (parsed.latestVersion) {
        console.log(
          `  - Skip v${parsed.latestVersion}: node "${installerScriptPath}" update --skip-version ${parsed.latestVersion}`,
        );
      }
      console.log(
        `  - Auto-update: node "${installerScriptPath}" config --auto-update auto`,
      );
      console.log(
        `  - Turn off   : node "${installerScriptPath}" config --auto-update off`,
      );
    }
  }

  if (parsed.status === "error") {
    throw new Error(parsed.error || parsed.message);
  }

  const isGlobalTarget = !opts.isProject && !opts.isCustomTarget;
  const syncIsolated = isGlobalTarget && !opts.skipAcp;
  if (
    syncIsolated &&
    !opts.checkOnly &&
    (parsed.status === "updated" || parsed.status === "up-to-date" || opts.force)
  ) {
    const isolatedTargets = await discoverIsolatedPluginDirs(resolvedDst);
    if (isolatedTargets.length > 0) {
      let linkTarget;
      try {
        linkTarget = await fs.realpath(resolvedDst);
      } catch (err) {
        if (err?.code === "ENOENT") {
          throw new Error(
            `Primary plugin path ${resolvedDst} is a broken symlink. Run 'install' to repair it.`,
          );
        }
        throw err;
      }
      const linkTargetCompare = toComparePath(linkTarget);
      for (const isolated of isolatedTargets) {
        const info = await inspectIsolatedPluginDir(isolated);
        const resolvedLinkTarget =
          (info.status === "ok" || info.status === "disabled") && info.mode === "symlink"
            ? await canonicalizeExistingPath(isolated.pluginDir)
            : null;
        const alreadyLinkedToGlobal =
          resolvedLinkTarget !== null &&
          toComparePath(resolvedLinkTarget) === linkTargetCompare;
        if (!alreadyLinkedToGlobal) {
          await syncIsolatedPluginDir(linkTarget, linkTarget, isolated, {
            ...opts,
            useLink: false,
          });
        }
      }
    }
  }

  const skipBinShims = Boolean(opts.isProject && !opts.binShimDir);
  let shimInstallRes = null;
  if (
    !opts.checkOnly &&
    (parsed.status === "updated" || parsed.status === "up-to-date" || opts.force)
  ) {
    if (opts.binShim || opts.binShimDir) {
      shimInstallRes = await installBinShims(resolvedDst, opts);
    } else if (parsed.status === "updated" && !skipBinShims && process.platform !== "win32") {
      // If existing owned POSIX symlink shims point to this plugin and an update replaced
      // target scripts without +x bits, restore +x without creating new shims.
      const matchingShims = await findMatchingBinShims(resolvedDst);
      for (const shim of matchingShims) {
        if (shim.kind === "symlink" && shim.status === "broken" && shim.targetPath) {
          const targetStat = await statSafe(shim.targetPath);
          if (targetStat?.isFile() && (targetStat.mode & 0o111) === 0) {
            await fs.chmod(shim.targetPath, 0o755);
          }
        }
      }
    }
  }

  if (parsed.status === "updated") {
    const checkBinShims = Boolean(shimInstallRes?.attempted || opts.binShimDir);
    const { ok } = await runDoctor(resolvedDst, opts.quiet, {
      checkIsolated: syncIsolated,
      binShimDir: opts.binShimDir,
      checkBinShims,
      skipBinShims,
    });
    if (!ok) {
      throw new Error("Post-update health check failed.");
    }
    if (!opts.quiet) {
      console.log("");
      console.log("Update complete. Start a new session (or reload Desktop/IDE window) to load the updated MCP server.");
    }
  }
}

async function runUninstall(opts) {
  const resolvedDst = path.resolve(opts.targetDir);
  const dstStat = await lstatSafe(resolvedDst);
  const isGlobalTarget = !opts.isProject && !opts.isCustomTarget;
  const syncIsolated = isGlobalTarget && !opts.skipAcp;
  const isolatedTargets = syncIsolated ? await discoverIsolatedPluginDirs(resolvedDst) : [];
  const existingIsolated = [];
  for (const isolated of isolatedTargets) {
    const isoStat = await lstatSafe(isolated.pluginDir);
    if (isoStat) {
      existingIsolated.push({ isolated, stat: isoStat });
    }
  }

  const matchingShims = await findMatchingBinShims(resolvedDst, opts.binShimDir);

  if (!dstStat && existingIsolated.length === 0 && matchingShims.length === 0) {
    if (!opts.quiet) {
      console.log(`Nothing to remove (${resolvedDst} does not exist).`);
    }
    return;
  }

  const resolvedSrc = await fs.realpath(REPO_ROOT);
  const srcCompare = toComparePath(resolvedSrc);
  const hasSrcDir = await pathExists(path.join(resolvedSrc, "src"));

  const guardTarget = async (targetPath, stat) => {
    if (!stat.isSymbolicLink()) {
      const targetCompare = toComparePath(await fs.realpath(targetPath));
      if (srcCompare === targetCompare && hasSrcDir) {
        throw new Error(
          `Refusing to delete the active source repository at ${targetPath}. Remove it manually if desired.`,
        );
      }
      if (isStrictAncestorPath(targetCompare, srcCompare)) {
        throw new Error(
          `Refusing to delete ${targetPath}: target is an ancestor directory of ${resolvedSrc}.`,
        );
      }
    }
    await assertRemovableTarget(targetPath, stat);
  };

  if (dstStat) {
    await guardTarget(resolvedDst, dstStat);
  }
  for (const { isolated, stat } of existingIsolated) {
    await guardTarget(isolated.pluginDir, stat);
  }

  if (dstStat && hasCommand("agy", ["--version"]) && !opts.skipEnable && isGlobalTarget) {
    spawnCliSync("agy", ["plugin", "disable", PLUGIN_NAME], {
      stdio: "ignore",
      timeout: 10_000,
    });
  }

  for (const { isolated, stat } of existingIsolated) {
    try {
      await removeTargetPath(isolated.pluginDir, stat, { quiet: opts.quiet });
    } catch (err) {
      if (isLockedTargetError(err)) {
        throw formatLockedTargetError(isolated.pluginDir, err);
      }
      throw err;
    }
    if (!opts.quiet) {
      console.log(`Removed agy-fast from ${isolated.pluginDir} (${isolated.label})`);
    }
  }

  if (dstStat) {
    try {
      await removeTargetPath(resolvedDst, dstStat, { quiet: opts.quiet });
    } catch (err) {
      if (isLockedTargetError(err)) {
        throw formatLockedTargetError(resolvedDst, err);
      }
      throw err;
    }
    if (!opts.quiet) {
      console.log(`Removed agy-fast from ${resolvedDst}`);
    }
  }

  if (matchingShims.length > 0) {
    const removedByDir = new Map();
    for (const shim of matchingShims) {
      try {
        await fs.unlink(shim.shimPath);
        const list = removedByDir.get(shim.binDir) || [];
        list.push(shim.fileName);
        removedByDir.set(shim.binDir, list);
      } catch (err) {
        if (err?.code !== "ENOENT") {
          throw err;
        }
      }
    }
    if (!opts.quiet) {
      for (const [dir, names] of removedByDir) {
        console.log(`Removed bin shim(s) from ${dir}: ${names.join(", ")}`);
      }
    }
  }
}

function parseMcpConfigTools(rawTools) {
  if (rawTools === null) return null;
  const trimmed = String(rawTools).trim();
  if (!trimmed) {
    throw new Error(
      `Invalid --tools value "${rawTools}". Expected comma-separated tool names from: ${EXPECTED_MCP_TOOLS.join(", ")}.`,
    );
  }
  const parts = trimmed.split(",").map((s) => s.trim());
  if (parts.some((p) => !p)) {
    throw new Error(
      `Invalid --tools value "${rawTools}": empty tool entry in comma-separated list. Valid tools: ${EXPECTED_MCP_TOOLS.join(", ")}.`,
    );
  }
  const invalid = parts.filter((name) => !EXPECTED_MCP_TOOLS.includes(name));
  if (invalid.length > 0) {
    throw new Error(
      `Unknown tool(s) in --tools: ${invalid.join(", ")}. Valid tools: ${EXPECTED_MCP_TOOLS.join(", ")}.`,
    );
  }
  return [...new Set(parts)];
}

async function resolveMcpEntryPosix(opts) {
  const targetMcp = path.join(path.resolve(opts.targetDir), "dist", "mcp-server.mjs");
  const repoMcp = path.join(REPO_ROOT, "dist", "mcp-server.mjs");
  let chosen = targetMcp;
  if (!opts.isCustomTarget && !opts.isProject) {
    if (!(await pathExists(targetMcp)) && (await pathExists(repoMcp))) {
      chosen = repoMcp;
    }
  }
  const exists = await pathExists(chosen);
  return { posix: chosen.split(path.sep).join("/"), exists };
}

function renderMcpConfigSnippet(host, mcpEntryPosix, opts, selectedTools = null) {
  const args = [mcpEntryPosix];
  if (selectedTools !== null) {
    args.push("--tools", selectedTools.join(","));
  }
  if (opts.schemaCompat === "minimal") {
    args.push("--schema-compat=minimal");
  }
  if (host === "antigravity") {
    const serverCfg = {
      command: "node",
      args,
    };
    if (opts.toolLoading !== "lazy") {
      const eagerTools = selectedTools ?? EXPECTED_MCP_TOOLS;
      serverCfg.tools = Object.fromEntries(
        eagerTools.map((name) => [name, { eager: true }]),
      );
    }
    return `${JSON.stringify(
      {
        mcpServers: {
          fast: serverCfg,
        },
      },
      null,
      2,
    )}\n`;
  }
  return `${JSON.stringify(
    {
      mcpServers: {
        "agy-fast": {
          command: "node",
          args,
        },
      },
    },
    null,
    2,
  )}\n`;
}

function escapePosixDoubleQuoted(str) {
  return str.replace(/(["\\$`])/g, "\\$1");
}

function renderGenericRulesTemplate(selectedTools, mcpEntryPosix) {
  const enabled = new Set(selectedTools || EXPECTED_MCP_TOOLS);
  const rows = [];
  if (enabled.has("quick_outline")) {
    rows.push(
      "| Map symbol/section line ranges in unknown large files (>800 lines, or >=3 >300-line files; max 40) | `quick_outline` | Avoids blind full-file reads |",
    );
  }
  if (enabled.has("read_slices")) {
    rows.push(
      "| Read multiple <=120-line symbol ranges across files in one call | `read_slices` | Inline cap <=8.8 KB UTF-8 |",
    );
  }
  if (enabled.has("batch_search")) {
    rows.push(
      "| Run >=2 text/regex/glob/fuzzy/read-only git queries (even across repos) | `batch_search` | `pattern` always required; `contextLines` 0..10 |",
    );
  }
  if (enabled.has("apply_edits")) {
    rows.push(
      "| Apply >=2 non-contiguous hunks, multi-file edits, or edit + inline `verify` | `apply_edits` | `create` XOR `hunks`; omit bounds on unique blocks |",
    );
  }
  if (enabled.has("run_checks")) {
    rows.push(
      "| Run >=2 independent non-interactive shell commands concurrently | `run_checks` | Default `compact`; shared 150s budget |",
    );
  }

  const bullets = [
    "- **Pass explicit `cwd` when `roots/list` is unavailable**: Provide an absolute workspace `cwd` on tool calls when running in hosts without MCP `roots/list` (or pass explicit full absolute target paths).",
  ];
  if (enabled.has("quick_outline")) {
    bullets.push(
      "- **Outline before reading**: For unknown files >800 lines (or >=3 >300-line files), run `quick_outline` first to map exact line ranges, then fetch targeted ranges.",
    );
  }
  if (enabled.has("read_slices")) {
    bullets.push(
      "- **Use `read_slices` for targeted small ranges**: Prefer `lineRanges: ['path:start-end,s2-e2']` for <=150 total lines (max 30 slices/lineRanges, max 40 outlines); for larger reads, use native ranged file reads instead of bulk-slicing >150 lines (8.8 KB inline cap).",
    );
  }
  if (enabled.has("batch_search")) {
    bullets.push(
      "- **Batch searches & respect schema bounds**: Pack multiple queries into one `batch_search` using per-query `path`; `pattern` is always required (e.g., `\"*\"` for `glob`), glob uses `*`/`{a,b}` (no `|`), `contextLines` is `0..10`, and for large `git diff`/`git show` run `--stat` or path-scoped diffs first.",
    );
  }
  if (enabled.has("apply_edits")) {
    bullets.push(
      "- **Safe multi-file edits**: Never call `apply_edits` in read-only plan modes; writes stay inside `cwd` by default (`AGY_FAST_ALLOW_OUTSIDE_CWD=1` to opt out). Use `create` XOR `hunks` per entry; omit `startLine`/`endLine` on unique code blocks (unique drifts `<=50` lines auto-recover); pass `bestEffort: true` when touching >=3 files so one mismatch does not roll back valid edits, pass `diff: true` for compact `+-2`-line diffs when helpful, and keep inline `verify` commands fast (<=45s; `verifyTimeoutSec` max `150`s).",
    );
  }
  if (enabled.has("run_checks")) {
    bullets.push(
      "- **Use `run_checks` for >=2 commands**: Keep single lightweight commands in the native shell (or use `run_checks` when 1 command emits >10 KB noisy logs); default to `outputMode: \"compact\"` (use `\"full\"` only when passing stdout is needed) and stay within the shared `150`s MCP budget.",
    );
  }
  if (enabled.has("batch_search") || enabled.has("apply_edits") || enabled.has("run_checks")) {
    bullets.push(
      "- **Inspect saved spill files on demand**: When a truncated output ends with `Full output saved: <path>`, inspect the saved file via targeted ranged reads or `batch_search`.",
    );
  }

  const cliMap = [
    ["batch_search", "search"],
    ["quick_outline", "outline"],
    ["read_slices", "slice"],
    ["apply_edits", "edit"],
    ["run_checks", "check"],
  ];
  const cliSubcmds = cliMap
    .filter(([tool]) => enabled.has(tool))
    .map(([, sub]) => sub);
  if (cliSubcmds.length > 0) {
    const cliNotes = [];
    if (enabled.has("batch_search")) {
      cliNotes.push("put per-query modifiers before each query");
    }
    cliNotes.push("supports `--from-file`/`--file <json>` for JSON payloads");
    bullets.push(
      `- **CLI fallback for subagents/scripts**: Invoke \`node "${escapePosixDoubleQuoted(mcpEntryPosix)}" --cli <${cliSubcmds.join("|")}> ...\` (${cliNotes.join("; ")}).`,
    );
  }

  return [
    "# agy-fast Tool Routing Rules",
    "",
    "Batch independent operations into one `agy-fast` MCP call whenever possible (output hard-capped at <=8.8 KB UTF-8):",
    "",
    "| Task | Preferred Tool | Notes |",
    "| :--- | :--- | :--- |",
    ...rows,
    "",
    "## Guidelines",
    "",
    ...bullets,
    "",
  ].join("\n");
}

async function runMcpConfig(opts) {
  const host = opts.mcpHost || "mcp-only";
  const tools = parseMcpConfigTools(opts.mcpToolsRaw);
  if (opts.printRules && opts.mcpHost && !opts.quiet) {
    console.error(`Warning: --host '${opts.mcpHost}' is ignored when --rules is set.`);
  }
  const entry = await resolveMcpEntryPosix(opts);
  if (!entry.exists && !opts.quiet) {
    console.error(
      `Warning: MCP server entrypoint not found at ${entry.posix} (run 'install' or 'npm run build' first).`,
    );
  }
  if (opts.printRules) {
    process.stdout.write(renderGenericRulesTemplate(tools, entry.posix));
    return;
  }
  process.stdout.write(renderMcpConfigSnippet(host, entry.posix, opts, tools));
}

async function main() {
  if (process.argv[2] === "mcp") {
    const mcpServerPath = path.join(REPO_ROOT, "dist", "mcp-server.mjs");
    if (!(await pathExists(mcpServerPath))) {
      throw new Error(
        `Built MCP server not found at ${mcpServerPath}. Run 'npm run build' first.`,
      );
    }
    process.argv = [process.argv[0], mcpServerPath, ...process.argv.slice(3)];
    await import(pathToFileURL(mcpServerPath).href);
    return;
  }

  const opts = parseArgs(process.argv);
  if (opts.showHelp) {
    printHelp();
    return;
  }

  if (
    opts.command !== "mcp-config" &&
    (opts.mcpHost || opts.mcpToolsRaw !== null || opts.schemaCompat || opts.printRules)
  ) {
    throw new Error(
      "--host, --tools, --schema-compat, and --rules are only supported with the 'mcp-config' command.",
    );
  }

  if (
    (opts.binShim || opts.binShimDir) &&
    !["install", "update", "status", "doctor", "uninstall"].includes(opts.command)
  ) {
    throw new Error(
      "--bin-shim and --bin-shim-dir are only supported with install, update, status, doctor, and uninstall.",
    );
  }

  switch (opts.command) {
    case "install":
      await runInstall(opts);
      break;
    case "update":
      await runUpdate(opts);
      break;
    case "config":
      await runConfig(opts);
      break;
    case "mcp-config":
      await runMcpConfig(opts);
      break;
    case "uninstall":
      await runUninstall(opts);
      break;
    case "status":
    case "doctor": {
      const checkIsolated = !opts.isProject && !opts.isCustomTarget && !opts.skipAcp;
      const { ok } = await runDoctor(opts.targetDir, opts.quiet, {
        checkIsolated,
        checkStorage: true,
        checkHygiene: true,
        workspaceDir: process.cwd(),
        binShimDir: opts.binShimDir,
        checkBinShims: true,
        skipBinShims: Boolean(opts.isProject && !opts.binShimDir),
      });
      if (!ok) process.exitCode = 1;
      break;
    }
    default:
      throw new Error(`Unknown command: ${opts.command}. Run with --help for usage.`);
  }
}

function isDirectExecution() {
  const entry = process.argv[1];
  if (!entry) return false;
  const selfPath = fileURLToPath(import.meta.url);
  try {
    return (
      toComparePath(fsSync.realpathSync(entry)) ===
      toComparePath(fsSync.realpathSync(selfPath))
    );
  } catch {
    return toComparePath(path.resolve(entry)) === toComparePath(selfPath);
  }
}

export {
  getDefaultBinShimDirs,
  inspectBinShim,
  isInsideNodeModules,
  parseShimWrapper,
  renderPosixShimWrapper,
  renderWindowsCmdShim,
  writeFileAtomically,
};

if (isDirectExecution()) {
  main().catch((err) => {
    console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
    process.exit(1);
  });
}