'use strict';

var fs4 = require('fs');
var path3 = require('path');
var child_process = require('child_process');
var util = require('util');
var os = require('os');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var fs4__default = /*#__PURE__*/_interopDefault(fs4);
var path3__default = /*#__PURE__*/_interopDefault(path3);
var os__default = /*#__PURE__*/_interopDefault(os);

// src/platform/core/helpers.ts
function stringifyUnknown(value) {
  if (value === void 0 || value === null) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Buffer.isBuffer(value)) {
    return value.toString("utf8");
  }
  if (value instanceof Error) {
    return value.stack || value.message;
  }
  return util.inspect(value, { depth: 6, breakLength: 120 });
}
function getErrorSummary(error) {
  if (error instanceof Error) {
    return `${error.name}: ${error.message}`;
  }
  return stringifyUnknown(error) || "Unknown error";
}

// src/platform/core/timestamp-helpers.ts
function padTimestampPart(value) {
  return String(value).padStart(2, "0");
}
function getTimestampParts(now = /* @__PURE__ */ new Date()) {
  return {
    year: now.getFullYear(),
    month: padTimestampPart(now.getMonth() + 1),
    day: padTimestampPart(now.getDate()),
    hour: padTimestampPart(now.getHours()),
    minute: padTimestampPart(now.getMinutes()),
    second: padTimestampPart(now.getSeconds())
  };
}
function getHumanReadableNow(now = /* @__PURE__ */ new Date()) {
  const { year, month, day, hour, minute, second } = getTimestampParts(now);
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// src/features/mcp/domain/server-record.ts
var SUPPORTED_HTTP_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
function normalizeMcpServerName(value) {
  const normalized = value.trim();
  if (!normalized) {
    throw new Error("MCP \uC11C\uBC84 \uC774\uB984\uC744 \uC785\uB825\uD574 \uC8FC\uC138\uC694.");
  }
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(normalized)) {
    throw new Error("MCP \uC11C\uBC84 \uC774\uB984\uC740 \uC601\uBB38, \uC22B\uC790, \uC810(.), \uBC11\uC904(_), \uD558\uC774\uD508(-)\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4.");
  }
  return normalized;
}
function normalizeMcpUrl(value) {
  const normalized = value.trim();
  if (!normalized) {
    throw new Error("MCP \uC11C\uBC84 \uC8FC\uC18C\uB97C \uC785\uB825\uD574 \uC8FC\uC138\uC694.");
  }
  let parsed;
  try {
    parsed = new URL(normalized);
  } catch (error) {
    throw new Error(`\uC720\uD6A8\uD55C MCP \uC11C\uBC84 URL\uC774 \uC544\uB2D9\uB2C8\uB2E4. ${getErrorSummary(error)}`);
  }
  if (!SUPPORTED_HTTP_PROTOCOLS.has(parsed.protocol)) {
    throw new Error(`\uD604\uC7AC\uB294 HTTP/HTTPS MCP \uC11C\uBC84\uB9CC \uC9C0\uC6D0\uD569\uB2C8\uB2E4. protocol=${parsed.protocol}`);
  }
  return parsed.toString();
}
function normalizeMcpCommand(value) {
  const normalized = value.trim();
  if (!normalized) {
    throw new Error("stdio MCP \uC11C\uBC84 command\uB97C \uC785\uB825\uD574 \uC8FC\uC138\uC694.");
  }
  return normalized;
}
function normalizeMcpArgs(values = []) {
  return values.map((value) => value.trim()).filter(Boolean);
}
function createMcpServerRecord(input, timestamps) {
  const name = normalizeMcpServerName(input.name);
  if (input.transport === "http") {
    return {
      createdAt: timestamps.createdAt,
      name,
      transport: "http",
      updatedAt: timestamps.updatedAt,
      url: normalizeMcpUrl(input.url)
    };
  }
  return {
    args: normalizeMcpArgs(input.args),
    command: normalizeMcpCommand(input.command),
    createdAt: timestamps.createdAt,
    name,
    transport: "stdio",
    updatedAt: timestamps.updatedAt
  };
}
function parsePersistedMcpServerRecord(value) {
  if (!value || typeof value !== "object") {
    return void 0;
  }
  const raw = value;
  if (typeof raw.name !== "string" || typeof raw.createdAt !== "string" || typeof raw.updatedAt !== "string") {
    return void 0;
  }
  if ((raw.transport === "http" || typeof raw.url === "string") && typeof raw.url === "string") {
    return createMcpServerRecord(
      {
        name: raw.name,
        transport: "http",
        url: raw.url
      },
      {
        createdAt: raw.createdAt,
        updatedAt: raw.updatedAt
      }
    );
  }
  if (raw.transport === "stdio" && typeof raw.command === "string") {
    return createMcpServerRecord(
      {
        args: Array.isArray(raw.args) ? raw.args.filter((entry) => typeof entry === "string") : [],
        command: raw.command,
        name: raw.name,
        transport: "stdio"
      },
      {
        createdAt: raw.createdAt,
        updatedAt: raw.updatedAt
      }
    );
  }
  return void 0;
}
function isStdioMcpServer(server) {
  return server.transport === "stdio";
}
function isHttpMcpServer(server) {
  return server.transport === "http";
}
function describeMcpServerRecord(server) {
  return isHttpMcpServer(server) ? server.url : [server.command, ...server.args].join(" ");
}
function getMcpServerHealthLabel(server) {
  return isHttpMcpServer(server) ? "Endpoint" : "Launcher";
}
function isSameMcpServerConfig(left, right) {
  if (left.name !== right.name || left.transport !== right.transport) {
    return false;
  }
  if (isHttpMcpServer(left) && isHttpMcpServer(right)) {
    return left.url === right.url;
  }
  if (isStdioMcpServer(left) && isStdioMcpServer(right)) {
    return left.command === right.command && left.args.join("\0") === right.args.join("\0");
  }
  return false;
}
var MCP_REGISTRY_VERSION = 1;
var MCP_HEALTH_CHECK_TIMEOUT_MS = 5e3;
var MCP_REGISTER_BY_SERVICE = {
  claude: configureClaudeServer,
  codex: configureCodexServer,
  gemini: configureGeminiServer
};
function getMcpPaths(paths) {
  return {
    directoryPath: paths.mcpDir,
    registryPath: paths.mcpRegistryPath
  };
}
function loadMcpRegistry(paths) {
  const mcpPaths = getMcpPaths(paths);
  if (!fs4__default.default.existsSync(mcpPaths.registryPath)) {
    return {
      servers: [],
      version: MCP_REGISTRY_VERSION
    };
  }
  try {
    const parsed = JSON.parse(fs4__default.default.readFileSync(mcpPaths.registryPath, "utf8"));
    const servers = Array.isArray(parsed.servers) ? parsed.servers.map((server) => parsePersistedMcpServerRecord(server)).filter((server) => Boolean(server)).filter((server) => server.name) : [];
    return {
      servers: servers.sort((left, right) => left.name.localeCompare(right.name)),
      version: typeof parsed.version === "number" ? parsed.version : MCP_REGISTRY_VERSION
    };
  } catch {
    return {
      servers: [],
      version: MCP_REGISTRY_VERSION
    };
  }
}
function saveMcpRegistry(paths, registry) {
  const mcpPaths = getMcpPaths(paths);
  fs4__default.default.mkdirSync(mcpPaths.directoryPath, { recursive: true });
  fs4__default.default.writeFileSync(
    mcpPaths.registryPath,
    `${JSON.stringify(
      {
        servers: [...registry.servers].sort((left, right) => left.name.localeCompare(right.name)),
        version: MCP_REGISTRY_VERSION
      },
      null,
      2
    )}
`,
    "utf8"
  );
}
function stripJsonComments(value) {
  let result = "";
  let inString = false;
  let inLineComment = false;
  let inBlockComment = false;
  let quote = "";
  for (let index = 0; index < value.length; index += 1) {
    const character = value[index] || "";
    const nextCharacter = value[index + 1] || "";
    const previousCharacter = value[index - 1] || "";
    if (inLineComment) {
      if (character === "\n") {
        inLineComment = false;
        result += character;
      }
      continue;
    }
    if (inBlockComment) {
      if (character === "*" && nextCharacter === "/") {
        inBlockComment = false;
        index += 1;
      }
      continue;
    }
    if (inString) {
      result += character;
      if (character === quote && previousCharacter !== "\\") {
        inString = false;
        quote = "";
      }
      continue;
    }
    if ((character === '"' || character === "'") && previousCharacter !== "\\") {
      inString = true;
      quote = character;
      result += character;
      continue;
    }
    if (character === "/" && nextCharacter === "/") {
      inLineComment = true;
      index += 1;
      continue;
    }
    if (character === "/" && nextCharacter === "*") {
      inBlockComment = true;
      index += 1;
      continue;
    }
    result += character;
  }
  return result;
}
function readGeminiSettingsFile() {
  const settingsPath = path3__default.default.join(os__default.default.homedir(), ".gemini", "settings.json");
  if (!fs4__default.default.existsSync(settingsPath)) {
    return {
      settings: {},
      settingsPath
    };
  }
  try {
    const parsed = JSON.parse(stripJsonComments(fs4__default.default.readFileSync(settingsPath, "utf8").trim() || "{}"));
    return {
      settings: parsed,
      settingsPath
    };
  } catch {
    return {
      settings: {},
      settingsPath
    };
  }
}
function writeGeminiSettingsFile(settings) {
  const { settingsPath } = readGeminiSettingsFile();
  fs4__default.default.mkdirSync(path3__default.default.dirname(settingsPath), { recursive: true });
  fs4__default.default.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}
`, "utf8");
  return settingsPath;
}
function runCliCommand(command, args) {
  const result = child_process.spawnSync(command, args, {
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 10
  });
  return {
    detail: [result.stdout, result.stderr].map((value) => value?.trim()).filter(Boolean).join("\n"),
    ok: !result.error && result.status === 0,
    result
  };
}
function buildStdioMcpCommandArgs(server) {
  return isHttpMcpServer(server) ? [] : ["--", server.command, ...server.args];
}
function buildGeminiMcpServerConfig(server) {
  if (isHttpMcpServer(server)) {
    return {
      type: "http",
      url: server.url
    };
  }
  return {
    args: server.args,
    command: server.command
  };
}
function isCommandLauncherAvailable(command) {
  if (!command.trim()) {
    return false;
  }
  if (path3__default.default.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
    return fs4__default.default.existsSync(command);
  }
  const locator = process.platform === "win32" ? "where" : "which";
  const result = child_process.spawnSync(locator, [command], {
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 2
  });
  return !result.error && result.status === 0;
}
function isServiceCliAvailable(service) {
  const binaryName = service === "codex" ? "codex" : service === "gemini" ? "gemini" : "claude";
  const result = child_process.spawnSync(binaryName, ["--version"], {
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 2
  });
  return !result.error && result.status === 0;
}
function configureCodexServer(server, parsedArgs, trace) {
  if (parsedArgs.testMode) {
    return {
      detail: `\uD14C\uC2A4\uD2B8 \uBAA8\uB4DC\uB77C codex ${isHttpMcpServer(server) ? "HTTP" : "stdio"} MCP \uB4F1\uB85D\uC744 \uC0DD\uB7B5\uD588\uC2B5\uB2C8\uB2E4. target=${describeMcpServerRecord(server)}`,
      ok: true,
      service: "codex",
      skipped: true
    };
  }
  if (!isServiceCliAvailable("codex")) {
    return {
      detail: "codex CLI\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
      ok: false,
      service: "codex"
    };
  }
  trace("mcp:codex:register:start", server.name);
  runCliCommand("codex", ["mcp", "remove", server.name]);
  const addArgs = isHttpMcpServer(server) ? ["mcp", "add", server.name, "--url", server.url] : ["mcp", "add", server.name, ...buildStdioMcpCommandArgs(server)];
  const addResult = runCliCommand("codex", addArgs);
  const verifyResult = runCliCommand("codex", ["mcp", "get", server.name]);
  const { ok } = verifyResult;
  trace("mcp:codex:register:end", `${server.name} | ${ok}`);
  return {
    detail: ok ? `\uB4F1\uB85D \uC644\uB8CC: ${server.name}` : addResult.detail || verifyResult.detail || "\uB4F1\uB85D \uD6C4 \uAC80\uC99D\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
    ok,
    service: "codex"
  };
}
function configureClaudeServer(server, parsedArgs, trace) {
  if (parsedArgs.testMode) {
    return {
      detail: `\uD14C\uC2A4\uD2B8 \uBAA8\uB4DC\uB77C claude ${isHttpMcpServer(server) ? "HTTP" : "stdio"} MCP \uB4F1\uB85D\uC744 \uC0DD\uB7B5\uD588\uC2B5\uB2C8\uB2E4. target=${describeMcpServerRecord(server)}`,
      ok: true,
      service: "claude",
      skipped: true
    };
  }
  if (!isServiceCliAvailable("claude")) {
    return {
      detail: "claude CLI\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
      ok: false,
      service: "claude"
    };
  }
  trace("mcp:claude:register:start", server.name);
  runCliCommand("claude", ["mcp", "remove", "--scope", "user", server.name]);
  const addArgs = isHttpMcpServer(server) ? ["mcp", "add", "--transport", "http", "--scope", "user", server.name, server.url] : ["mcp", "add", "--transport", "stdio", "--scope", "user", server.name, ...buildStdioMcpCommandArgs(server)];
  const addResult = runCliCommand("claude", addArgs);
  const verifyResult = runCliCommand("claude", ["mcp", "get", server.name]);
  const { ok } = verifyResult;
  trace("mcp:claude:register:end", `${server.name} | ${ok}`);
  return {
    detail: ok ? `\uB4F1\uB85D \uC644\uB8CC: ${server.name}` : addResult.detail || verifyResult.detail || "\uB4F1\uB85D \uD6C4 \uAC80\uC99D\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
    ok,
    service: "claude"
  };
}
function configureGeminiServer(server, parsedArgs, trace) {
  if (parsedArgs.testMode) {
    return {
      detail: `\uD14C\uC2A4\uD2B8 \uBAA8\uB4DC\uB77C ~/.gemini/settings.json \uC758 mcpServers.${server.name} \uBC18\uC601\uC744 \uC0DD\uB7B5\uD588\uC2B5\uB2C8\uB2E4.`,
      ok: true,
      service: "gemini",
      skipped: true
    };
  }
  trace("mcp:gemini:register:start", server.name);
  const { settings } = readGeminiSettingsFile();
  const nextSettings = {
    ...settings,
    mcpServers: {
      ...settings.mcpServers || {},
      [server.name]: buildGeminiMcpServerConfig(server)
    }
  };
  const settingsPath = writeGeminiSettingsFile(nextSettings);
  const configured = Boolean(readGeminiSettingsFile().settings.mcpServers?.[server.name]);
  trace("mcp:gemini:register:end", `${server.name} | ${configured}`);
  return {
    detail: configured ? `\uB4F1\uB85D \uC644\uB8CC: ${settingsPath}` : "settings.json \uBC18\uC601 \uD6C4 \uAC80\uC99D\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
    ok: configured,
    service: "gemini"
  };
}
function registerMcpServerForService(server, service, parsedArgs, trace) {
  return MCP_REGISTER_BY_SERVICE[service](server, parsedArgs, trace);
}
function checkCodexServer(server) {
  if (!isServiceCliAvailable("codex")) {
    return {
      detail: "codex CLI\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
      ok: false,
      service: "codex"
    };
  }
  const result = runCliCommand("codex", ["mcp", "get", server.name]);
  return {
    detail: result.ok ? `\uB4F1\uB85D\uB428: ${server.name}` : result.detail || "\uB4F1\uB85D \uC815\uBCF4\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
    ok: result.ok,
    service: "codex"
  };
}
function checkClaudeServer(server) {
  if (!isServiceCliAvailable("claude")) {
    return {
      detail: "claude CLI\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
      ok: false,
      service: "claude"
    };
  }
  const result = runCliCommand("claude", ["mcp", "get", server.name]);
  return {
    detail: result.ok ? `\uB4F1\uB85D\uB428: ${server.name}` : result.detail || "\uB4F1\uB85D \uC815\uBCF4\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.",
    ok: result.ok,
    service: "claude"
  };
}
function checkGeminiServer(server) {
  const geminiServer = readGeminiSettingsFile().settings.mcpServers?.[server.name];
  const configured = JSON.stringify(geminiServer || {}) === JSON.stringify(buildGeminiMcpServerConfig(server));
  return {
    detail: configured ? `\uB4F1\uB85D\uB428: ${server.name}` : "settings.json \uC5D0 \uAE30\uB300\uD55C \uB4F1\uB85D \uC815\uBCF4\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.",
    ok: configured,
    service: "gemini"
  };
}
function getMcpServiceStatuses(server) {
  return [checkCodexServer(server), checkGeminiServer(server), checkClaudeServer(server)];
}
async function probeMcpEndpoint(url) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), MCP_HEALTH_CHECK_TIMEOUT_MS);
  try {
    const response = await fetch(url, {
      headers: {
        Accept: "application/json, text/event-stream, */*"
      },
      method: "GET",
      signal: controller.signal
    });
    return {
      label: "Endpoint",
      detail: `HTTP ${response.status} ${response.statusText}`.trim(),
      ok: true,
      statusCode: response.status
    };
  } catch (error) {
    return {
      label: "Endpoint",
      detail: getErrorSummary(error),
      ok: false
    };
  } finally {
    clearTimeout(timer);
  }
}
function probeMcpLauncher(server) {
  if (isHttpMcpServer(server)) {
    throw new Error("stdio launcher probe\uB294 stdio MCP \uC11C\uBC84\uC5D0\uC11C\uB9CC \uD638\uCD9C\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4.");
  }
  const available = isCommandLauncherAvailable(server.command);
  return {
    label: getMcpServerHealthLabel(server),
    detail: available ? `\uC2E4\uD589 \uAC00\uB2A5: ${server.command}` : `${server.command} \uC2E4\uD589 \uD30C\uC77C\uC744 \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.`,
    ok: available
  };
}
async function runMcpHealthCheck(server, trace) {
  trace("mcp:health-check:start", server.name);
  const endpoint = isHttpMcpServer(server) ? await probeMcpEndpoint(server.url) : probeMcpLauncher(server);
  const services = getMcpServiceStatuses(server);
  trace("mcp:health-check:end", `${server.name} | endpoint=${endpoint.ok}`);
  return {
    endpoint,
    server,
    services
  };
}
function upsertRegisteredMcpServerRecord(paths, input) {
  const registry = loadMcpRegistry(paths);
  const normalizedName = normalizeMcpServerName(input.name);
  const nextServerRecord = createMcpServerRecord(
    {
      ...input,
      name: normalizedName
    },
    {
      createdAt: "",
      updatedAt: ""
    }
  );
  const existingByName = registry.servers.find((server2) => server2.name === normalizedName);
  const existingByUrl = nextServerRecord.transport === "http" ? registry.servers.find((server2) => isHttpMcpServer(server2) && server2.url === nextServerRecord.url) : void 0;
  const now = getHumanReadableNow();
  if (existingByUrl && existingByUrl.name !== normalizedName) {
    throw new Error(`\uAC19\uC740 URL\uC774 \uC774\uBBF8 \uB2E4\uB978 \uC774\uB984\uC73C\uB85C \uB4F1\uB85D\uB418\uC5B4 \uC788\uC2B5\uB2C8\uB2E4. existing=${existingByUrl.name}`);
  }
  if (existingByName) {
    const updatedRecord = createMcpServerRecord(input, {
      createdAt: existingByName.createdAt,
      updatedAt: now
    });
    const targetIndex = registry.servers.findIndex((server2) => server2.name === normalizedName);
    registry.servers.splice(targetIndex, 1, updatedRecord);
    saveMcpRegistry(paths, registry);
    return {
      created: false,
      server: updatedRecord
    };
  }
  const server = createMcpServerRecord(input, {
    createdAt: now,
    updatedAt: now
  });
  registry.servers.push(server);
  saveMcpRegistry(paths, registry);
  return {
    created: true,
    server
  };
}
function findRegisteredMcpServer(paths, serverName) {
  return loadMcpRegistry(paths).servers.find((server) => server.name === serverName);
}

// src/features/gen-html/domain/storybook-mcp.ts
var STORYBOOK_MCP_SERVER_NAME = "storybook-mcp";
var STORYBOOK_MCP_SERVER_URL = "https://main--685dde4728854606b608af64.chromatic.com/mcp";
function createStorybookMcpServerInput() {
  return {
    name: STORYBOOK_MCP_SERVER_NAME,
    transport: "http",
    url: STORYBOOK_MCP_SERVER_URL
  };
}

// src/features/gen-html/infrastructure/storybook-mcp.ts
function getCurrentServiceStatus(healthCheck, service) {
  return healthCheck.services.find((result) => result.service === service);
}
function isStorybookMcpReadyForService(healthCheck, service) {
  const currentServiceStatus = getCurrentServiceStatus(healthCheck, service);
  return healthCheck.endpoint.ok && Boolean(currentServiceStatus?.ok);
}
function createSkippedStorybookMcpHealthCheck(server, syncResults) {
  return {
    endpoint: {
      detail: "\uD14C\uC2A4\uD2B8 \uBAA8\uB4DC\uB77C Storybook MCP endpoint \uD5EC\uC2A4\uCCB4\uD06C\uB97C \uC0DD\uB7B5\uD588\uC2B5\uB2C8\uB2E4.",
      label: getMcpServerHealthLabel(server),
      ok: true
    },
    server,
    services: syncResults
  };
}
function ensureStorybookMcpRegistryRecord(paths) {
  const desiredInput = createStorybookMcpServerInput();
  const existingServer = findRegisteredMcpServer(paths, desiredInput.name);
  const desiredServer = createMcpServerRecord(desiredInput, {
    createdAt: existingServer?.createdAt || "",
    updatedAt: existingServer?.updatedAt || ""
  });
  if (existingServer && isSameMcpServerConfig(existingServer, desiredServer)) {
    return {
      created: false,
      server: existingServer,
      updated: false
    };
  }
  const registration = upsertRegisteredMcpServerRecord(paths, desiredInput);
  return {
    created: registration.created,
    server: registration.server,
    updated: true
  };
}
async function ensureStorybookMcpServer(options) {
  const registryResult = ensureStorybookMcpRegistryRecord(options.paths);
  if (options.parsedArgs.testMode) {
    const syncResults2 = [registerMcpServerForService(registryResult.server, options.service, options.parsedArgs, options.trace)];
    return {
      healthCheck: createSkippedStorybookMcpHealthCheck(registryResult.server, syncResults2),
      registrationCreated: registryResult.created,
      registrationUpdated: registryResult.updated && !registryResult.created,
      repaired: false,
      server: registryResult.server,
      syncResults: syncResults2
    };
  }
  let syncResults = registryResult.updated ? [registerMcpServerForService(registryResult.server, options.service, options.parsedArgs, options.trace)] : [];
  let healthCheck = await runMcpHealthCheck(registryResult.server, options.trace);
  let repaired = false;
  if (!isStorybookMcpReadyForService(healthCheck, options.service)) {
    repaired = true;
    syncResults = [registerMcpServerForService(registryResult.server, options.service, options.parsedArgs, options.trace)];
    healthCheck = await runMcpHealthCheck(registryResult.server, options.trace);
  }
  return {
    healthCheck,
    registrationCreated: registryResult.created,
    registrationUpdated: registryResult.updated && !registryResult.created,
    repaired,
    server: registryResult.server,
    syncResults
  };
}

exports.ensureStorybookMcpServer = ensureStorybookMcpServer;
exports.isStorybookMcpReadyForService = isStorybookMcpReadyForService;
