import "./agent-scope-DTd9OXHs.js";
import { u as normalizeAgentId } from "./session-key-BOpfMTUN.js";
import { c as resolveDefaultAgentId, n as listAgentIds, t as listAgentEntries } from "./agent-scope-config-By9b6pJY.js";
import { r as getActiveMemorySearchManager } from "./memory-runtime-BHeTZvn2.js";
import { t as resolveMemorySearchConfig } from "./memory-search-B_P2rSod.js";
import { t as resolveMemoryBackendConfig } from "./backend-config-BvKiw0UB.js";
//#region src/gateway/server-startup-memory.ts
/** True when qmd memory config opts into startup boot sync work. */
function shouldRunQmdStartupBootSync(qmd) {
	return qmd.update.onBoot && qmd.update.startup !== "off";
}
/** Check whether an agent overrides memory search instead of inheriting defaults. */
function hasExplicitAgentMemorySearchConfig(cfg, agentId) {
	return listAgentEntries(cfg).some((entry) => normalizeAgentId(entry.id) === agentId && entry.memorySearch != null);
}
/** Decide whether an agent's qmd memory manager should start during Gateway boot. */
function shouldEagerlyStartAgentMemory(params) {
	if (params.agentCount <= 1) return true;
	if (params.agentId === resolveDefaultAgentId(params.cfg)) return true;
	if (params.cfg.agents?.defaults?.memorySearch?.enabled === true) return true;
	return hasExplicitAgentMemorySearchConfig(params.cfg, params.agentId);
}
/** Start qmd memory boot sync for eligible agents without eagerly loading every agent. */
async function startGatewayMemoryBackend(params) {
	const agentIds = listAgentIds(params.cfg);
	const armedAgentIds = [];
	const deferredAgentIds = [];
	for (const agentId of agentIds) {
		if (!resolveMemorySearchConfig(params.cfg, agentId)) continue;
		const resolved = resolveMemoryBackendConfig({
			cfg: params.cfg,
			agentId
		});
		if (!resolved) continue;
		if (resolved.backend !== "qmd" || !resolved.qmd) continue;
		if (!shouldRunQmdStartupBootSync(resolved.qmd)) continue;
		if (!shouldEagerlyStartAgentMemory({
			cfg: params.cfg,
			agentId,
			agentCount: agentIds.length
		})) {
			deferredAgentIds.push(agentId);
			continue;
		}
		const { manager, error } = await getActiveMemorySearchManager({
			cfg: params.cfg,
			agentId,
			purpose: "cli"
		});
		if (!manager) {
			params.log.warn(`qmd memory startup initialization failed for agent "${agentId}": ${error ?? "unknown error"}`);
			continue;
		}
		try {
			await manager.sync?.({
				reason: "boot",
				force: true
			});
		} catch (err) {
			params.log.warn(`qmd memory startup boot sync failed for agent "${agentId}": ${String(err)}`);
			continue;
		} finally {
			await manager.close?.().catch((err) => {
				params.log.warn(`qmd memory startup manager close failed for agent "${agentId}": ${String(err)}`);
			});
		}
		armedAgentIds.push(agentId);
	}
	if (armedAgentIds.length > 0) params.log.info?.(`qmd memory startup boot sync completed for ${formatAgentCount(armedAgentIds.length)}: ${armedAgentIds.map((agentId) => `"${agentId}"`).join(", ")}`);
	if (deferredAgentIds.length > 0) params.log.info?.(`qmd memory startup initialization deferred for ${formatAgentCount(deferredAgentIds.length)}: ${deferredAgentIds.map((agentId) => `"${agentId}"`).join(", ")}`);
}
function formatAgentCount(count) {
	return count === 1 ? "1 agent" : `${count} agents`;
}
//#endregion
export { startGatewayMemoryBackend };
