import { i as normalizeLowercaseStringOrEmpty, s as normalizeOptionalString } from "./string-coerce-CIT1-v_a.js";
import { d as pathExists } from "./utils-CE5zxr9Z.js";
import { r as runCommandWithTimeout } from "./exec-B1X3fcmA.js";
import { t as resolveStableNodePath } from "./stable-node-path-CoKMq9Jw.js";
import { U as applyPathPrepend } from "./exec-defaults-BdlJJu0T.js";
import { o as trimLogTail } from "./restart-sentinel-Ca8WUWbf.js";
import { f as isBetaTag, l as DEV_BRANCH, n as compareSemverStrings, p as isStableTag, s as detectPackageManager, u as channelToNpmTag } from "./update-check-CFiv7MVY.js";
import { i as resolveControlUiDistIndexPathForRoot, r as resolveControlUiDistIndexHealth } from "./control-ui-assets-A53m8hYI.js";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import fs$1 from "node:fs/promises";
//#region src/infra/package-json.ts
async function readPackageVersion(root) {
	try {
		const raw = await fs$1.readFile(path.join(root, "package.json"), "utf-8");
		const version = JSON.parse(raw)?.version?.trim();
		return version ? version : null;
	} catch {
		return null;
	}
}
async function readPackageName(root) {
	try {
		const raw = await fs$1.readFile(path.join(root, "package.json"), "utf-8");
		const name = JSON.parse(raw)?.name?.trim();
		return name ? name : null;
	} catch {
		return null;
	}
}
//#endregion
//#region src/infra/package-tag.ts
function normalizePackageTagInput(value, packageNames) {
	const trimmed = normalizeOptionalString(value);
	if (!trimmed) return null;
	for (const packageName of packageNames) {
		if (trimmed === packageName) return null;
		const prefix = `${packageName}@`;
		if (trimmed.startsWith(prefix)) {
			const tag = trimmed.slice(prefix.length).trim();
			return tag ? tag : null;
		}
	}
	return trimmed;
}
//#endregion
//#region scripts/lib/bundled-runtime-sidecar-paths.json
var bundled_runtime_sidecar_paths_default = [
	"dist/extensions/browser/runtime-api.js",
	"dist/extensions/copilot-proxy/runtime-api.js",
	"dist/extensions/diffs/runtime-api.js",
	"dist/extensions/feishu/runtime-api.js",
	"dist/extensions/google/runtime-api.js",
	"dist/extensions/lmstudio/runtime-api.js",
	"dist/extensions/memory-core/runtime-api.js",
	"dist/extensions/ollama/runtime-api.js",
	"dist/extensions/open-prose/runtime-api.js",
	"dist/extensions/webhooks/runtime-api.js",
	"dist/extensions/zai/runtime-api.js"
];
//#endregion
//#region src/plugins/runtime-sidecar-paths.ts
function assertUniqueValues(values, label) {
	const seen = /* @__PURE__ */ new Set();
	const duplicates = /* @__PURE__ */ new Set();
	for (const value of values) {
		if (seen.has(value)) {
			duplicates.add(value);
			continue;
		}
		seen.add(value);
	}
	if (duplicates.size > 0) throw new Error(`Duplicate ${label}: ${Array.from(duplicates).join(", ")}`);
	return values;
}
const BUNDLED_RUNTIME_SIDECAR_PATHS = assertUniqueValues(bundled_runtime_sidecar_paths_default, "bundled runtime sidecar path");
//#endregion
//#region src/infra/update-global.ts
const PRIMARY_PACKAGE_NAME = "kaijibot";
const ALL_PACKAGE_NAMES = [PRIMARY_PACKAGE_NAME];
const GLOBAL_RENAME_PREFIX = ".";
const KAIJIBOT_MAIN_PACKAGE_SPEC = "github:kaijibot/kaijibot#main";
const NPM_GLOBAL_INSTALL_QUIET_FLAGS = [
	"--no-fund",
	"--no-audit",
	"--loglevel=error"
];
const NPM_GLOBAL_INSTALL_OMIT_OPTIONAL_FLAGS = ["--omit=optional", ...NPM_GLOBAL_INSTALL_QUIET_FLAGS];
function normalizePackageTarget(value) {
	return value.trim();
}
function isMainPackageTarget(value) {
	return normalizeLowercaseStringOrEmpty(normalizePackageTarget(value)) === "main";
}
function isExplicitPackageInstallSpec(value) {
	const trimmed = normalizePackageTarget(value);
	if (!trimmed) return false;
	return trimmed.includes("://") || trimmed.includes("#") || /^(?:file|github|git\+ssh|git\+https|git\+http|git\+file|npm):/i.test(trimmed);
}
function resolveExpectedInstalledVersionFromSpec(packageName, spec) {
	const normalizedPackageName = packageName.trim();
	const normalizedSpec = normalizePackageTarget(spec);
	if (!normalizedPackageName || !normalizedSpec.startsWith(`${normalizedPackageName}@`)) return null;
	const rawVersion = normalizedSpec.slice(normalizedPackageName.length + 1).trim();
	if (!rawVersion || rawVersion.includes("/") || rawVersion.includes(":") || rawVersion.includes("#") || /^(latest|beta|next|main)$/i.test(rawVersion)) return null;
	return rawVersion;
}
async function collectInstalledGlobalPackageErrors(params) {
	const errors = [];
	const installedVersion = await readPackageVersion(params.packageRoot);
	if (params.expectedVersion && installedVersion !== params.expectedVersion) errors.push(`expected installed version ${params.expectedVersion}, found ${installedVersion ?? "<missing>"}`);
	for (const relativePath of BUNDLED_RUNTIME_SIDECAR_PATHS) if (!await pathExists(path.join(params.packageRoot, relativePath))) errors.push(`missing bundled runtime sidecar ${relativePath}`);
	return errors;
}
function canResolveRegistryVersionForPackageTarget(value) {
	const trimmed = normalizePackageTarget(value);
	if (!trimmed) return true;
	return !isMainPackageTarget(trimmed) && !isExplicitPackageInstallSpec(trimmed);
}
async function resolvePortableGitPathPrepend(env) {
	if (process.platform !== "win32") return [];
	const localAppData = env?.LOCALAPPDATA?.trim() || process.env.LOCALAPPDATA?.trim();
	if (!localAppData) return [];
	const portableGitRoot = path.join(localAppData, "KaijiBot", "deps", "portable-git");
	const candidates = [
		path.join(portableGitRoot, "mingw64", "bin"),
		path.join(portableGitRoot, "usr", "bin"),
		path.join(portableGitRoot, "cmd"),
		path.join(portableGitRoot, "bin")
	];
	const existing = [];
	for (const candidate of candidates) if (await pathExists(candidate)) existing.push(candidate);
	return existing;
}
function applyWindowsPackageInstallEnv(env) {
	if (process.platform !== "win32") return;
	env.NPM_CONFIG_UPDATE_NOTIFIER = "false";
	env.NPM_CONFIG_FUND = "false";
	env.NPM_CONFIG_AUDIT = "false";
	env.NODE_LLAMA_CPP_SKIP_DOWNLOAD = "1";
}
function resolveGlobalInstallSpec(params) {
	const override = params.env?.KAIJIBOT_UPDATE_PACKAGE_SPEC?.trim() || process.env.KAIJIBOT_UPDATE_PACKAGE_SPEC?.trim();
	if (override) return override;
	const target = normalizePackageTarget(params.tag);
	if (isMainPackageTarget(target)) return KAIJIBOT_MAIN_PACKAGE_SPEC;
	if (isExplicitPackageInstallSpec(target)) return target;
	return `${params.packageName}@${target}`;
}
async function createGlobalInstallEnv(env) {
	const pathPrepend = await resolvePortableGitPathPrepend(env);
	if (pathPrepend.length === 0 && process.platform !== "win32") return env;
	const merged = Object.fromEntries(Object.entries(env ?? process.env).filter(([, value]) => value != null).map(([key, value]) => [key, String(value)]));
	applyPathPrepend(merged, pathPrepend);
	applyWindowsPackageInstallEnv(merged);
	return merged;
}
async function tryRealpath(targetPath) {
	try {
		return await fs$1.realpath(targetPath);
	} catch {
		return path.resolve(targetPath);
	}
}
function resolveBunGlobalRoot() {
	const bunInstall = process.env.BUN_INSTALL?.trim() || path.join(os.homedir(), ".bun");
	return path.join(bunInstall, "install", "global", "node_modules");
}
function inferNpmPrefixFromPackageRoot(pkgRoot) {
	const trimmed = pkgRoot?.trim();
	if (!trimmed) return null;
	const normalized = path.resolve(trimmed);
	const nodeModulesDir = path.dirname(normalized);
	if (path.basename(nodeModulesDir) !== "node_modules") return null;
	const parentDir = path.dirname(nodeModulesDir);
	if (path.basename(parentDir) === "lib") return path.dirname(parentDir);
	if (process.platform === "win32" && normalizeLowercaseStringOrEmpty(path.basename(parentDir)) === "npm") return parentDir;
	return null;
}
function resolvePreferredNpmCommand(pkgRoot) {
	const prefix = inferNpmPrefixFromPackageRoot(pkgRoot);
	if (!prefix) return null;
	const candidate = process.platform === "win32" ? path.join(prefix, "npm.cmd") : path.join(prefix, "bin", "npm");
	return fs.existsSync(candidate) ? candidate : null;
}
function resolvePreferredGlobalManagerCommand(manager, pkgRoot) {
	if (manager !== "npm") return manager;
	return resolvePreferredNpmCommand(pkgRoot) ?? manager;
}
function resolveGlobalInstallCommand(manager, pkgRoot) {
	return {
		manager,
		command: resolvePreferredGlobalManagerCommand(manager, pkgRoot)
	};
}
function normalizeGlobalInstallCommand(managerOrCommand, pkgRoot) {
	return typeof managerOrCommand === "string" ? resolveGlobalInstallCommand(managerOrCommand, pkgRoot) : managerOrCommand;
}
async function resolveGlobalRoot(managerOrCommand, runCommand, timeoutMs, pkgRoot) {
	const resolved = normalizeGlobalInstallCommand(managerOrCommand, pkgRoot);
	if (resolved.manager === "bun") return resolveBunGlobalRoot();
	const res = await runCommand([
		resolved.command,
		"root",
		"-g"
	], { timeoutMs }).catch(() => null);
	if (!res || res.code !== 0) return null;
	return res.stdout.trim() || null;
}
async function resolveGlobalInstallTarget(params) {
	const command = normalizeGlobalInstallCommand(params.manager, params.pkgRoot);
	const globalRoot = await resolveGlobalRoot(command, params.runCommand, params.timeoutMs, params.pkgRoot);
	return {
		...command,
		globalRoot,
		packageRoot: globalRoot ? path.join(globalRoot, PRIMARY_PACKAGE_NAME) : null
	};
}
async function detectGlobalInstallManagerForRoot(runCommand, pkgRoot, timeoutMs) {
	const pkgReal = await tryRealpath(pkgRoot);
	for (const { manager, argv } of [{
		manager: "npm",
		argv: [
			"npm",
			"root",
			"-g"
		]
	}, {
		manager: "pnpm",
		argv: [
			"pnpm",
			"root",
			"-g"
		]
	}]) {
		const res = await runCommand(argv, { timeoutMs }).catch(() => null);
		if (!res || res.code !== 0) continue;
		const globalRoot = res.stdout.trim();
		if (!globalRoot) continue;
		const globalReal = await tryRealpath(globalRoot);
		for (const name of ALL_PACKAGE_NAMES) {
			const expectedReal = await tryRealpath(path.join(globalReal, name));
			if (path.resolve(expectedReal) === path.resolve(pkgReal)) return manager;
		}
	}
	const bunGlobalReal = await tryRealpath(resolveBunGlobalRoot());
	for (const name of ALL_PACKAGE_NAMES) {
		const bunExpectedReal = await tryRealpath(path.join(bunGlobalReal, name));
		if (path.resolve(bunExpectedReal) === path.resolve(pkgReal)) return "bun";
	}
	if (resolvePreferredNpmCommand(pkgRoot)) return "npm";
	return null;
}
async function detectGlobalInstallManagerByPresence(runCommand, timeoutMs) {
	for (const manager of ["npm", "pnpm"]) {
		const root = await resolveGlobalRoot(manager, runCommand, timeoutMs);
		if (!root) continue;
		for (const name of ALL_PACKAGE_NAMES) if (await pathExists(path.join(root, name))) return manager;
	}
	const bunRoot = resolveBunGlobalRoot();
	for (const name of ALL_PACKAGE_NAMES) if (await pathExists(path.join(bunRoot, name))) return "bun";
	return null;
}
function globalInstallArgs(managerOrCommand, spec, pkgRoot) {
	const resolved = normalizeGlobalInstallCommand(managerOrCommand, pkgRoot);
	if (resolved.manager === "pnpm") return [
		resolved.command,
		"add",
		"-g",
		spec
	];
	if (resolved.manager === "bun") return [
		resolved.command,
		"add",
		"-g",
		spec
	];
	return [
		resolved.command,
		"i",
		"-g",
		spec,
		...NPM_GLOBAL_INSTALL_QUIET_FLAGS
	];
}
function globalInstallFallbackArgs(managerOrCommand, spec, pkgRoot) {
	const resolved = normalizeGlobalInstallCommand(managerOrCommand, pkgRoot);
	if (resolved.manager !== "npm") return null;
	return [
		resolved.command,
		"i",
		"-g",
		spec,
		...NPM_GLOBAL_INSTALL_OMIT_OPTIONAL_FLAGS
	];
}
async function cleanupGlobalRenameDirs(params) {
	const removed = [];
	const root = params.globalRoot.trim();
	const name = params.packageName.trim();
	if (!root || !name) return { removed };
	const prefix = `${GLOBAL_RENAME_PREFIX}${name}-`;
	let entries = [];
	try {
		entries = await fs$1.readdir(root);
	} catch {
		return { removed };
	}
	for (const entry of entries) {
		if (!entry.startsWith(prefix)) continue;
		const target = path.join(root, entry);
		try {
			if (!(await fs$1.lstat(target)).isDirectory()) continue;
			await fs$1.rm(target, {
				recursive: true,
				force: true
			});
			removed.push(entry);
		} catch {}
	}
	return { removed };
}
//#endregion
//#region src/infra/update-package-manager.ts
async function detectBuildManager(root) {
	return await detectPackageManager(root) ?? "npm";
}
function managerPreferenceOrder(preferred) {
	if (preferred === "pnpm") return [
		"pnpm",
		"npm",
		"bun"
	];
	if (preferred === "bun") return [
		"bun",
		"npm",
		"pnpm"
	];
	return [
		"npm",
		"pnpm",
		"bun"
	];
}
function managerVersionArgs(manager) {
	if (manager === "pnpm") return ["pnpm", "--version"];
	if (manager === "bun") return ["bun", "--version"];
	return ["npm", "--version"];
}
async function isManagerAvailable(runCommand, manager, timeoutMs, env) {
	try {
		return (await runCommand(managerVersionArgs(manager), {
			timeoutMs,
			env
		})).code === 0;
	} catch {
		return false;
	}
}
async function isCommandAvailable(runCommand, argv, timeoutMs, env) {
	try {
		return (await runCommand(argv, {
			timeoutMs,
			env
		})).code === 0;
	} catch {
		return false;
	}
}
function cloneCommandEnv(env) {
	return Object.fromEntries(Object.entries(env ?? process.env).filter(([, value]) => value != null).map(([key, value]) => [key, String(value)]));
}
async function enablePnpmViaCorepack(runCommand, timeoutMs, env) {
	if (!await isCommandAvailable(runCommand, ["corepack", "--version"], timeoutMs, env)) return "missing";
	try {
		if ((await runCommand(["corepack", "enable"], {
			timeoutMs,
			env
		})).code !== 0) return "failed";
	} catch {
		return "failed";
	}
	return await isManagerAvailable(runCommand, "pnpm", timeoutMs, env) ? "enabled" : "failed";
}
async function bootstrapPnpmViaNpm(params) {
	const tempRoot = await fs$1.mkdtemp(path.join(os.tmpdir(), "kaijibot-update-pnpm-"));
	const cleanup = async () => {
		await fs$1.rm(tempRoot, {
			recursive: true,
			force: true
		}).catch(() => {});
	};
	try {
		if ((await params.runCommand([
			"npm",
			"install",
			"--prefix",
			tempRoot,
			"pnpm@10"
		], {
			timeoutMs: params.timeoutMs,
			env: params.baseEnv
		})).code !== 0) {
			await cleanup();
			return null;
		}
		const env = cloneCommandEnv(params.baseEnv);
		applyPathPrepend(env, [path.join(tempRoot, "node_modules", ".bin")]);
		if (!await isManagerAvailable(params.runCommand, "pnpm", params.timeoutMs, env)) {
			await cleanup();
			return null;
		}
		return {
			env,
			cleanup
		};
	} catch {
		await cleanup();
		return null;
	}
}
async function resolveUpdateBuildManager(runCommand, root, timeoutMs, baseEnv, requirement = "allow-fallback") {
	const preferred = await detectBuildManager(root);
	if (preferred === "pnpm") {
		if (await isManagerAvailable(runCommand, "pnpm", timeoutMs, baseEnv)) return {
			kind: "resolved",
			manager: "pnpm",
			preferred,
			fallback: false
		};
		const corepackStatus = await enablePnpmViaCorepack(runCommand, timeoutMs, baseEnv);
		if (corepackStatus === "enabled") return {
			kind: "resolved",
			manager: "pnpm",
			preferred,
			fallback: false
		};
		if (await isManagerAvailable(runCommand, "npm", timeoutMs, baseEnv)) {
			const pnpmBootstrap = await bootstrapPnpmViaNpm({
				runCommand,
				timeoutMs,
				baseEnv
			});
			if (pnpmBootstrap) return {
				kind: "resolved",
				manager: "pnpm",
				preferred,
				fallback: false,
				env: pnpmBootstrap.env,
				cleanup: pnpmBootstrap.cleanup
			};
			if (requirement === "require-preferred") return {
				kind: "missing-required",
				preferred,
				reason: "pnpm-npm-bootstrap-failed"
			};
		}
		if (requirement === "require-preferred") {
			if (corepackStatus === "missing") return {
				kind: "missing-required",
				preferred,
				reason: "pnpm-corepack-missing"
			};
			if (corepackStatus === "failed") return {
				kind: "missing-required",
				preferred,
				reason: "pnpm-corepack-enable-failed"
			};
			return {
				kind: "missing-required",
				preferred,
				reason: "preferred-manager-unavailable"
			};
		}
	}
	for (const manager of managerPreferenceOrder(preferred)) if (await isManagerAvailable(runCommand, manager, timeoutMs, baseEnv)) return {
		kind: "resolved",
		manager,
		preferred,
		fallback: manager !== preferred
	};
	if (requirement === "require-preferred") return {
		kind: "missing-required",
		preferred,
		reason: "preferred-manager-unavailable"
	};
	return {
		kind: "resolved",
		manager: "npm",
		preferred,
		fallback: preferred !== "npm"
	};
}
function managerScriptArgs(manager, script, args = []) {
	if (manager === "pnpm") return [
		"pnpm",
		script,
		...args
	];
	if (manager === "bun") return [
		"bun",
		"run",
		script,
		...args
	];
	if (args.length > 0) return [
		"npm",
		"run",
		script,
		"--",
		...args
	];
	return [
		"npm",
		"run",
		script
	];
}
function managerInstallArgs(manager, opts) {
	if (manager === "pnpm") return ["pnpm", "install"];
	if (manager === "bun") return ["bun", "install"];
	if (opts?.compatFallback) return [
		"npm",
		"install",
		"--no-package-lock",
		"--legacy-peer-deps"
	];
	return ["npm", "install"];
}
function managerInstallIgnoreScriptsArgs(manager) {
	if (manager === "pnpm") return [
		"pnpm",
		"install",
		"--ignore-scripts"
	];
	if (manager === "bun") return [
		"bun",
		"install",
		"--ignore-scripts"
	];
	return [
		"npm",
		"install",
		"--ignore-scripts"
	];
}
//#endregion
//#region src/infra/update-runner.ts
function mapManagerResolutionFailure(reason) {
	return reason;
}
const DEFAULT_TIMEOUT_MS = 20 * 6e4;
const MAX_LOG_CHARS = 8e3;
const PREFLIGHT_MAX_COMMITS = 10;
const START_DIRS = [
	"cwd",
	"argv1",
	"process"
];
const DEFAULT_PACKAGE_NAME = "kaijibot";
const CORE_PACKAGE_NAMES = new Set([DEFAULT_PACKAGE_NAME]);
const PREFLIGHT_TEMP_PREFIX = process.platform === "win32" ? "ocu-pf-" : "kaijibot-update-preflight-";
const PREFLIGHT_WORKTREE_DIRNAME = process.platform === "win32" ? "wt" : "worktree";
const WINDOWS_PREFLIGHT_BASE_DIR = "ocu";
const WINDOWS_BUILD_MAX_OLD_SPACE_MB = 4096;
function normalizeDir(value) {
	if (!value) return null;
	const trimmed = value.trim();
	if (!trimmed) return null;
	return path.resolve(trimmed);
}
function resolveNodeModulesBinPackageRoot(argv1) {
	const normalized = path.resolve(argv1);
	const parts = normalized.split(path.sep);
	const binIndex = parts.lastIndexOf(".bin");
	if (binIndex <= 0) return null;
	if (parts[binIndex - 1] !== "node_modules") return null;
	const binName = path.basename(normalized);
	const nodeModulesDir = parts.slice(0, binIndex).join(path.sep);
	return path.join(nodeModulesDir, binName);
}
function buildStartDirs(opts) {
	const dirs = [];
	const cwd = normalizeDir(opts.cwd);
	if (cwd) dirs.push(cwd);
	const argv1 = normalizeDir(opts.argv1);
	if (argv1) {
		dirs.push(path.dirname(argv1));
		const packageRoot = resolveNodeModulesBinPackageRoot(argv1);
		if (packageRoot) dirs.push(packageRoot);
	}
	const proc = normalizeDir(process.cwd());
	if (proc) dirs.push(proc);
	return Array.from(new Set(dirs));
}
function resolvePreflightTempRootPrefix() {
	return path.join(os.tmpdir(), PREFLIGHT_TEMP_PREFIX);
}
function resolvePreflightWorktreeDir(preflightRoot) {
	return path.join(preflightRoot, PREFLIGHT_WORKTREE_DIRNAME);
}
function shouldUseNativeWindowsTempRoot() {
	return process.platform === "win32" && path.sep === "\\";
}
async function createPreflightRoot() {
	if (shouldUseNativeWindowsTempRoot()) {
		const baseDir = path.win32.join(process.env.SystemDrive ?? "C:", WINDOWS_PREFLIGHT_BASE_DIR);
		await fs$1.mkdir(baseDir, { recursive: true });
		return fs$1.mkdtemp(path.win32.join(baseDir, PREFLIGHT_TEMP_PREFIX));
	}
	return fs$1.mkdtemp(resolvePreflightTempRootPrefix());
}
async function removePathRecursive(target) {
	await fs$1.rm(target, {
		recursive: true,
		force: true,
		maxRetries: 3,
		retryDelay: 200
	}).catch(() => {});
}
async function repairWindowsPreflightCleanup(worktreeDir, preflightRoot) {
	if (process.platform !== "win32") return false;
	try {
		await fs$1.rm(worktreeDir, {
			recursive: true,
			force: true,
			maxRetries: 3,
			retryDelay: 200
		});
		await fs$1.rm(preflightRoot, {
			recursive: true,
			force: true,
			maxRetries: 3,
			retryDelay: 200
		});
		return true;
	} catch {
		return false;
	}
}
async function readBranchName(runCommand, root, timeoutMs) {
	const res = await runCommand([
		"git",
		"-C",
		root,
		"rev-parse",
		"--abbrev-ref",
		"HEAD"
	], { timeoutMs }).catch(() => null);
	if (!res || res.code !== 0) return null;
	return res.stdout.trim() || null;
}
async function listGitTags(runCommand, root, timeoutMs, pattern = "v*") {
	const res = await runCommand([
		"git",
		"-C",
		root,
		"tag",
		"--list",
		pattern,
		"--sort=-v:refname"
	], { timeoutMs }).catch(() => null);
	if (!res || res.code !== 0) return [];
	return res.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
}
async function resolveChannelTag(runCommand, root, timeoutMs, channel) {
	const tags = await listGitTags(runCommand, root, timeoutMs);
	if (channel === "beta") {
		const betaTag = tags.find((tag) => isBetaTag(tag)) ?? null;
		const stableTag = tags.find((tag) => isStableTag(tag)) ?? null;
		if (!betaTag) return stableTag;
		if (!stableTag) return betaTag;
		const cmp = compareSemverStrings(betaTag, stableTag);
		if (cmp != null && cmp < 0) return stableTag;
		return betaTag;
	}
	return tags.find((tag) => isStableTag(tag)) ?? null;
}
async function resolveGitRoot(runCommand, candidates, timeoutMs) {
	for (const dir of candidates) {
		const res = await runCommand([
			"git",
			"-C",
			dir,
			"rev-parse",
			"--show-toplevel"
		], { timeoutMs }).catch(() => null);
		if (!res) continue;
		if (res.code === 0) {
			const root = res.stdout.trim();
			if (root) return root;
		}
	}
	return null;
}
async function findPackageRoot(candidates) {
	for (const dir of candidates) {
		let current = dir;
		for (let i = 0; i < 12; i += 1) {
			const pkgPath = path.join(current, "package.json");
			try {
				const raw = await fs$1.readFile(pkgPath, "utf-8");
				const name = JSON.parse(raw)?.name?.trim();
				if (name && CORE_PACKAGE_NAMES.has(name)) return current;
			} catch {}
			const parent = path.dirname(current);
			if (parent === current) break;
			current = parent;
		}
	}
	return null;
}
async function runStep(opts) {
	const { runCommand, name, argv, cwd, timeoutMs, env, progress, stepIndex, totalSteps } = opts;
	const command = argv.join(" ");
	const stepInfo = {
		name,
		command,
		index: stepIndex,
		total: totalSteps
	};
	progress?.onStepStart?.(stepInfo);
	const started = Date.now();
	const result = await runCommand(argv, {
		cwd,
		timeoutMs,
		env
	});
	const durationMs = Date.now() - started;
	const stderrTail = trimLogTail(result.stderr, MAX_LOG_CHARS);
	progress?.onStepComplete?.({
		...stepInfo,
		durationMs,
		exitCode: result.code,
		stderrTail
	});
	return {
		name,
		command,
		cwd,
		durationMs,
		exitCode: result.code,
		stdoutTail: trimLogTail(result.stdout, MAX_LOG_CHARS),
		stderrTail: trimLogTail(result.stderr, MAX_LOG_CHARS)
	};
}
function normalizeTag(tag) {
	return normalizePackageTagInput(tag, ["kaijibot", DEFAULT_PACKAGE_NAME]) ?? "latest";
}
function shouldRetryWindowsInstallIgnoringScripts(manager) {
	return process.platform === "win32" && manager === "pnpm";
}
function shouldPreferIgnoreScriptsForWindowsPreflight(manager) {
	return process.platform === "win32" && manager === "pnpm";
}
function resolveWindowsBuildNodeOptions(baseOptions) {
	const current = baseOptions?.trim() ?? "";
	const desired = `--max-old-space-size=${WINDOWS_BUILD_MAX_OLD_SPACE_MB}`;
	const existingMatch = /(?:^|\s)--max-old-space-size=(\d+)(?=\s|$)/.exec(current);
	if (!existingMatch) return current ? `${current} ${desired}` : desired;
	const existingValue = Number(existingMatch[1]);
	if (Number.isFinite(existingValue) && existingValue >= WINDOWS_BUILD_MAX_OLD_SPACE_MB) return current;
	return current.replace(/(?:^|\s)--max-old-space-size=\d+(?=\s|$)/, ` ${desired}`).trim();
}
function resolveWindowsBuildEnv(env) {
	if (process.platform !== "win32") return env;
	const currentNodeOptions = env?.NODE_OPTIONS ?? process.env.NODE_OPTIONS;
	const nextNodeOptions = resolveWindowsBuildNodeOptions(currentNodeOptions);
	if (nextNodeOptions === currentNodeOptions) return env;
	return {
		...env,
		NODE_OPTIONS: nextNodeOptions
	};
}
function isSupersededInstallFailure(step, steps) {
	if (step.exitCode === 0) return false;
	if (step.name === "deps install") return steps.some((candidate) => candidate.name === "deps install (ignore scripts)" && candidate.exitCode === 0);
	const preflightMatch = /^preflight deps install \((.+)\)$/.exec(step.name);
	if (!preflightMatch) return false;
	const retryName = `preflight deps install (ignore scripts) (${preflightMatch[1]})`;
	return steps.some((candidate) => candidate.name === retryName && candidate.exitCode === 0);
}
function findBlockingGitFailure(steps) {
	return steps.find((step) => step.exitCode !== 0 && !isSupersededInstallFailure(step, steps));
}
function mergeCommandEnvironments(baseEnv, overrideEnv) {
	if (!baseEnv) return overrideEnv;
	if (!overrideEnv) return baseEnv;
	return {
		...baseEnv,
		...overrideEnv
	};
}
async function runGatewayUpdate(opts = {}) {
	const startedAt = Date.now();
	const defaultCommandEnv = await createGlobalInstallEnv();
	const runCommand = opts.runCommand ?? (async (argv, options) => {
		const res = await runCommandWithTimeout(argv, {
			...options,
			env: mergeCommandEnvironments(defaultCommandEnv, options.env)
		});
		return {
			stdout: res.stdout,
			stderr: res.stderr,
			code: res.code
		};
	});
	const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
	const progress = opts.progress;
	const steps = [];
	const candidates = buildStartDirs(opts);
	let stepIndex = 0;
	let gitTotalSteps = 0;
	const step = (name, argv, cwd, env) => {
		const currentIndex = stepIndex;
		stepIndex += 1;
		return {
			runCommand,
			name,
			argv,
			cwd,
			timeoutMs,
			env,
			progress,
			stepIndex: currentIndex,
			totalSteps: gitTotalSteps
		};
	};
	const pkgRoot = await findPackageRoot(candidates);
	let gitRoot = await resolveGitRoot(runCommand, candidates, timeoutMs);
	if (gitRoot && pkgRoot && path.resolve(gitRoot) !== path.resolve(pkgRoot)) gitRoot = null;
	if (gitRoot && !pkgRoot) return {
		status: "error",
		mode: "unknown",
		root: gitRoot,
		reason: "not-kaijibot-root",
		steps: [],
		durationMs: Date.now() - startedAt
	};
	if (gitRoot && pkgRoot && path.resolve(gitRoot) === path.resolve(pkgRoot)) {
		const beforeSha = (await runCommand([
			"git",
			"-C",
			gitRoot,
			"rev-parse",
			"HEAD"
		], {
			cwd: gitRoot,
			timeoutMs
		})).stdout.trim() || null;
		const beforeVersion = await readPackageVersion(gitRoot);
		const channel = opts.channel ?? "dev";
		const branch = channel === "dev" ? await readBranchName(runCommand, gitRoot, timeoutMs) : null;
		const needsCheckoutMain = channel === "dev" && branch !== "main";
		gitTotalSteps = channel === "dev" ? needsCheckoutMain ? 11 : 10 : 9;
		const buildGitErrorResult = (reason) => ({
			status: "error",
			mode: "git",
			root: gitRoot,
			reason,
			before: {
				sha: beforeSha,
				version: beforeVersion
			},
			steps,
			durationMs: Date.now() - startedAt
		});
		const runGitCheckoutOrFail = async (name, argv) => {
			const checkoutStep = await runStep(step(name, argv, gitRoot));
			steps.push(checkoutStep);
			if (checkoutStep.exitCode !== 0) return buildGitErrorResult("checkout-failed");
			return null;
		};
		const statusCheck = await runStep(step("clean check", [
			"git",
			"-C",
			gitRoot,
			"status",
			"--porcelain",
			"--",
			":!dist/control-ui/"
		], gitRoot));
		steps.push(statusCheck);
		if (statusCheck.stdoutTail && statusCheck.stdoutTail.trim().length > 0) return {
			status: "skipped",
			mode: "git",
			root: gitRoot,
			reason: "dirty",
			before: {
				sha: beforeSha,
				version: beforeVersion
			},
			steps,
			durationMs: Date.now() - startedAt
		};
		if (channel === "dev") {
			if (needsCheckoutMain) {
				const failure = await runGitCheckoutOrFail(`git checkout ${DEV_BRANCH}`, [
					"git",
					"-C",
					gitRoot,
					"checkout",
					DEV_BRANCH
				]);
				if (failure) return failure;
			}
			const upstreamStep = await runStep(step("upstream check", [
				"git",
				"-C",
				gitRoot,
				"rev-parse",
				"--abbrev-ref",
				"--symbolic-full-name",
				"@{upstream}"
			], gitRoot));
			steps.push(upstreamStep);
			if (upstreamStep.exitCode !== 0) return {
				status: "skipped",
				mode: "git",
				root: gitRoot,
				reason: "no-upstream",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const fetchStep = await runStep(step("git fetch", [
				"git",
				"-C",
				gitRoot,
				"fetch",
				"--all",
				"--prune",
				"--tags"
			], gitRoot));
			steps.push(fetchStep);
			const upstreamShaStep = await runStep(step("git rev-parse @{upstream}", [
				"git",
				"-C",
				gitRoot,
				"rev-parse",
				"@{upstream}"
			], gitRoot));
			steps.push(upstreamShaStep);
			const upstreamSha = upstreamShaStep.stdoutTail?.trim();
			if (!upstreamShaStep.stdoutTail || !upstreamSha) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "no-upstream-sha",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const revListStep = await runStep(step("git rev-list", [
				"git",
				"-C",
				gitRoot,
				"rev-list",
				`--max-count=${PREFLIGHT_MAX_COMMITS}`,
				upstreamSha
			], gitRoot));
			steps.push(revListStep);
			if (revListStep.exitCode !== 0) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "preflight-revlist-failed",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const candidates = (revListStep.stdoutTail ?? "").split("\n").map((line) => line.trim()).filter(Boolean);
			if (candidates.length === 0) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "preflight-no-candidates",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const manager = await resolveUpdateBuildManager((argv, options) => runCommand(argv, {
				timeoutMs: options.timeoutMs,
				env: options.env
			}), gitRoot, timeoutMs, defaultCommandEnv, "require-preferred");
			if (manager.kind === "missing-required") return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: mapManagerResolutionFailure(manager.reason),
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const preflightRoot = await createPreflightRoot();
			const worktreeDir = resolvePreflightWorktreeDir(preflightRoot);
			const worktreeStep = await runStep(step("preflight worktree", [
				"git",
				"-C",
				gitRoot,
				"worktree",
				"add",
				"--detach",
				worktreeDir,
				upstreamSha
			], gitRoot));
			steps.push(worktreeStep);
			if (worktreeStep.exitCode !== 0) {
				await removePathRecursive(preflightRoot);
				return {
					status: "error",
					mode: "git",
					root: gitRoot,
					reason: "preflight-worktree-failed",
					before: {
						sha: beforeSha,
						version: beforeVersion
					},
					steps,
					durationMs: Date.now() - startedAt
				};
			}
			let selectedSha = null;
			try {
				for (const sha of candidates) {
					const shortSha = sha.slice(0, 8);
					const checkoutStep = await runStep(step(`preflight checkout (${shortSha})`, [
						"git",
						"-C",
						worktreeDir,
						"checkout",
						"--detach",
						sha
					], worktreeDir));
					steps.push(checkoutStep);
					if (checkoutStep.exitCode !== 0) continue;
					const preflightIgnoreScripts = shouldPreferIgnoreScriptsForWindowsPreflight(manager.manager);
					const preflightIgnoreScriptsArgv = managerInstallIgnoreScriptsArgs(manager.manager);
					const depsStepArgv = preflightIgnoreScripts && preflightIgnoreScriptsArgv ? preflightIgnoreScriptsArgv : managerInstallArgs(manager.manager, { compatFallback: manager.fallback && manager.manager === "npm" });
					const depsStep = await runStep(step(preflightIgnoreScripts ? `preflight deps install (ignore scripts) (${shortSha})` : `preflight deps install (${shortSha})`, depsStepArgv, worktreeDir, manager.env));
					steps.push(depsStep);
					let finalDepsStep = depsStep;
					if (depsStep.exitCode !== 0 && !preflightIgnoreScripts && shouldRetryWindowsInstallIgnoringScripts(manager.manager)) {
						const retryArgv = managerInstallIgnoreScriptsArgs(manager.manager);
						if (retryArgv) {
							const retryStep = await runStep(step(`preflight deps install (ignore scripts) (${shortSha})`, retryArgv, worktreeDir, manager.env));
							steps.push(retryStep);
							finalDepsStep = retryStep;
						}
					}
					if (finalDepsStep.exitCode !== 0) continue;
					const buildStep = await runStep(step(`preflight build (${shortSha})`, managerScriptArgs(manager.manager, "build"), worktreeDir, resolveWindowsBuildEnv(manager.env)));
					steps.push(buildStep);
					if (buildStep.exitCode !== 0) continue;
					const lintStep = await runStep(step(`preflight lint (${shortSha})`, managerScriptArgs(manager.manager, "lint"), worktreeDir, manager.env));
					steps.push(lintStep);
					if (lintStep.exitCode !== 0) continue;
					selectedSha = sha;
					break;
				}
			} finally {
				const removeStep = await runStep(step("preflight cleanup", [
					"git",
					"-C",
					gitRoot,
					"worktree",
					"remove",
					"--force",
					worktreeDir
				], gitRoot));
				if (removeStep.exitCode !== 0 && await repairWindowsPreflightCleanup(worktreeDir, preflightRoot)) {
					removeStep.exitCode = 0;
					removeStep.stderrTail = trimLogTail([removeStep.stderrTail, "windows fallback cleanup removed preflight tree"].filter(Boolean).join("\n"), MAX_LOG_CHARS);
				}
				steps.push(removeStep);
				await runCommand([
					"git",
					"-C",
					gitRoot,
					"worktree",
					"prune"
				], {
					cwd: gitRoot,
					timeoutMs
				}).catch(() => null);
				await removePathRecursive(preflightRoot);
				await manager.cleanup?.();
			}
			if (!selectedSha) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "preflight-no-good-commit",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const rebaseStep = await runStep(step("git rebase", [
				"git",
				"-C",
				gitRoot,
				"rebase",
				selectedSha
			], gitRoot));
			steps.push(rebaseStep);
			if (rebaseStep.exitCode !== 0) {
				const abortResult = await runCommand([
					"git",
					"-C",
					gitRoot,
					"rebase",
					"--abort"
				], {
					cwd: gitRoot,
					timeoutMs
				});
				steps.push({
					name: "git rebase --abort",
					command: "git rebase --abort",
					cwd: gitRoot,
					durationMs: 0,
					exitCode: abortResult.code,
					stdoutTail: trimLogTail(abortResult.stdout, MAX_LOG_CHARS),
					stderrTail: trimLogTail(abortResult.stderr, MAX_LOG_CHARS)
				});
				return {
					status: "error",
					mode: "git",
					root: gitRoot,
					reason: "rebase-failed",
					before: {
						sha: beforeSha,
						version: beforeVersion
					},
					steps,
					durationMs: Date.now() - startedAt
				};
			}
		} else {
			const fetchStep = await runStep(step("git fetch", [
				"git",
				"-C",
				gitRoot,
				"fetch",
				"--all",
				"--prune",
				"--tags"
			], gitRoot));
			steps.push(fetchStep);
			if (fetchStep.exitCode !== 0) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "fetch-failed",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const tag = await resolveChannelTag(runCommand, gitRoot, timeoutMs, channel);
			if (!tag) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "no-release-tag",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const failure = await runGitCheckoutOrFail(`git checkout ${tag}`, [
				"git",
				"-C",
				gitRoot,
				"checkout",
				"--detach",
				tag
			]);
			if (failure) return failure;
		}
		const manager = await resolveUpdateBuildManager((argv, options) => runCommand(argv, {
			timeoutMs: options.timeoutMs,
			env: options.env
		}), gitRoot, timeoutMs, defaultCommandEnv, "require-preferred");
		if (manager.kind === "missing-required") return {
			status: "error",
			mode: "git",
			root: gitRoot,
			reason: mapManagerResolutionFailure(manager.reason),
			before: {
				sha: beforeSha,
				version: beforeVersion
			},
			steps,
			durationMs: Date.now() - startedAt
		};
		try {
			const depsStep = await runStep(step("deps install", managerInstallArgs(manager.manager, { compatFallback: manager.fallback && manager.manager === "npm" }), gitRoot, manager.env));
			steps.push(depsStep);
			let finalDepsStep = depsStep;
			if (depsStep.exitCode !== 0 && shouldRetryWindowsInstallIgnoringScripts(manager.manager)) {
				const retryArgv = managerInstallIgnoreScriptsArgs(manager.manager);
				if (retryArgv) {
					const retryStep = await runStep(step("deps install (ignore scripts)", retryArgv, gitRoot, manager.env));
					steps.push(retryStep);
					finalDepsStep = retryStep;
				}
			}
			if (finalDepsStep.exitCode !== 0) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "deps-install-failed",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const buildStep = await runStep(step("build", managerScriptArgs(manager.manager, "build"), gitRoot, resolveWindowsBuildEnv(manager.env)));
			steps.push(buildStep);
			if (buildStep.exitCode !== 0) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "build-failed",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const uiBuildStep = await runStep(step("ui:build", managerScriptArgs(manager.manager, "ui:build"), gitRoot, manager.env));
			steps.push(uiBuildStep);
			if (uiBuildStep.exitCode !== 0) return {
				status: "error",
				mode: "git",
				root: gitRoot,
				reason: "ui-build-failed",
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
			const doctorEntry = path.join(gitRoot, "kaijibot.mjs");
			if (!await fs$1.stat(doctorEntry).then(() => true).catch(() => false)) {
				steps.push({
					name: "kaijibot doctor entry",
					command: `verify ${doctorEntry}`,
					cwd: gitRoot,
					durationMs: 0,
					exitCode: 1,
					stderrTail: `missing ${doctorEntry}`
				});
				return {
					status: "error",
					mode: "git",
					root: gitRoot,
					reason: "doctor-entry-missing",
					before: {
						sha: beforeSha,
						version: beforeVersion
					},
					steps,
					durationMs: Date.now() - startedAt
				};
			}
			const doctorStep = await runStep(step("kaijibot doctor", [
				await resolveStableNodePath(process.execPath),
				doctorEntry,
				"doctor",
				"--non-interactive",
				"--fix"
			], gitRoot, { KAIJIBOT_UPDATE_IN_PROGRESS: "1" }));
			steps.push(doctorStep);
			if (!(await resolveControlUiDistIndexHealth({ root: gitRoot })).exists) {
				const repairArgv = managerScriptArgs(manager.manager, "ui:build");
				const started = Date.now();
				const repairResult = await runCommand(repairArgv, {
					cwd: gitRoot,
					timeoutMs,
					env: manager.env
				});
				const repairStep = {
					name: "ui:build (post-doctor repair)",
					command: repairArgv.join(" "),
					cwd: gitRoot,
					durationMs: Date.now() - started,
					exitCode: repairResult.code,
					stdoutTail: trimLogTail(repairResult.stdout, MAX_LOG_CHARS),
					stderrTail: trimLogTail(repairResult.stderr, MAX_LOG_CHARS)
				};
				steps.push(repairStep);
				if (repairResult.code !== 0) return {
					status: "error",
					mode: "git",
					root: gitRoot,
					reason: repairStep.name,
					before: {
						sha: beforeSha,
						version: beforeVersion
					},
					steps,
					durationMs: Date.now() - startedAt
				};
				const repairedUiIndexHealth = await resolveControlUiDistIndexHealth({ root: gitRoot });
				if (!repairedUiIndexHealth.exists) {
					const uiIndexPath = repairedUiIndexHealth.indexPath ?? resolveControlUiDistIndexPathForRoot(gitRoot);
					steps.push({
						name: "ui assets verify",
						command: `verify ${uiIndexPath}`,
						cwd: gitRoot,
						durationMs: 0,
						exitCode: 1,
						stderrTail: `missing ${uiIndexPath}`
					});
					return {
						status: "error",
						mode: "git",
						root: gitRoot,
						reason: "ui-assets-missing",
						before: {
							sha: beforeSha,
							version: beforeVersion
						},
						steps,
						durationMs: Date.now() - startedAt
					};
				}
			}
			const failedStep = findBlockingGitFailure(steps);
			const afterShaStep = await runStep(step("git rev-parse HEAD (after)", [
				"git",
				"-C",
				gitRoot,
				"rev-parse",
				"HEAD"
			], gitRoot));
			steps.push(afterShaStep);
			const afterVersion = await readPackageVersion(gitRoot);
			return {
				status: failedStep ? "error" : "ok",
				mode: "git",
				root: gitRoot,
				reason: failedStep ? failedStep.name : void 0,
				before: {
					sha: beforeSha,
					version: beforeVersion
				},
				after: {
					sha: afterShaStep.stdoutTail?.trim() ?? null,
					version: afterVersion
				},
				steps,
				durationMs: Date.now() - startedAt
			};
		} finally {
			await manager.cleanup?.();
		}
	}
	if (!pkgRoot) return {
		status: "error",
		mode: "unknown",
		reason: `no root (${START_DIRS.join(",")})`,
		steps: [],
		durationMs: Date.now() - startedAt
	};
	const beforeVersion = await readPackageVersion(pkgRoot);
	const globalManager = await detectGlobalInstallManagerForRoot(runCommand, pkgRoot, timeoutMs);
	if (globalManager) {
		const installTarget = await resolveGlobalInstallTarget({
			manager: globalManager,
			runCommand,
			timeoutMs,
			pkgRoot
		});
		const packageName = await readPackageName(pkgRoot) ?? DEFAULT_PACKAGE_NAME;
		await cleanupGlobalRenameDirs({
			globalRoot: path.dirname(pkgRoot),
			packageName
		});
		const channel = opts.channel ?? "stable";
		const tag = normalizeTag(opts.tag ?? channelToNpmTag(channel));
		const steps = [];
		const globalInstallEnv = await createGlobalInstallEnv();
		const spec = resolveGlobalInstallSpec({
			packageName,
			tag,
			env: globalInstallEnv
		});
		const updateStep = await runStep({
			runCommand,
			name: "global update",
			argv: globalInstallArgs(installTarget, spec),
			cwd: pkgRoot,
			timeoutMs,
			env: globalInstallEnv,
			progress,
			stepIndex: 0,
			totalSteps: 1
		});
		steps.push(updateStep);
		let finalStep = updateStep;
		if (updateStep.exitCode !== 0) {
			const fallbackArgv = globalInstallFallbackArgs(installTarget, spec);
			if (fallbackArgv) {
				const fallbackStep = await runStep({
					runCommand,
					name: "global update (omit optional)",
					argv: fallbackArgv,
					cwd: pkgRoot,
					timeoutMs,
					env: globalInstallEnv,
					progress,
					stepIndex: 0,
					totalSteps: 1
				});
				steps.push(fallbackStep);
				finalStep = fallbackStep;
			}
		}
		const verifiedPackageRoot = (await resolveGlobalInstallTarget({
			manager: installTarget,
			runCommand,
			timeoutMs
		})).packageRoot ?? pkgRoot;
		const verificationErrors = await collectInstalledGlobalPackageErrors({
			packageRoot: verifiedPackageRoot,
			expectedVersion: resolveExpectedInstalledVersionFromSpec(packageName, spec)
		});
		if (verificationErrors.length > 0) steps.push({
			name: "global install verify",
			command: `verify ${verifiedPackageRoot}`,
			cwd: verifiedPackageRoot,
			durationMs: 0,
			exitCode: 1,
			stderrTail: verificationErrors.join("\n")
		});
		const afterVersion = await readPackageVersion(verifiedPackageRoot);
		const failedStep = finalStep.exitCode !== 0 ? finalStep : steps.find((step) => step.name === "global install verify" && step.exitCode !== 0) ?? null;
		return {
			status: failedStep ? "error" : "ok",
			mode: globalManager,
			root: verifiedPackageRoot,
			reason: failedStep ? failedStep.name : void 0,
			before: { version: beforeVersion },
			after: { version: afterVersion },
			steps,
			durationMs: Date.now() - startedAt
		};
	}
	return {
		status: "skipped",
		mode: "unknown",
		root: pkgRoot,
		reason: "not-git-install",
		before: { version: beforeVersion },
		steps: [],
		durationMs: Date.now() - startedAt
	};
}
//#endregion
export { createGlobalInstallEnv as a, globalInstallArgs as c, resolveGlobalInstallTarget as d, normalizePackageTagInput as f, collectInstalledGlobalPackageErrors as i, resolveExpectedInstalledVersionFromSpec as l, readPackageVersion as m, canResolveRegistryVersionForPackageTarget as n, detectGlobalInstallManagerByPresence as o, readPackageName as p, cleanupGlobalRenameDirs as r, detectGlobalInstallManagerForRoot as s, runGatewayUpdate as t, resolveGlobalInstallSpec as u };
