#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/server/launch-kit-paths.ts
var LAUNCHSECURE_DIR;
var init_launch_kit_paths = __esm({
  "src/server/launch-kit-paths.ts"() {
    "use strict";
    LAUNCHSECURE_DIR = ".launchsecure";
  }
});

// src/server/council-lockfile.ts
function lockDir(projectRoot) {
  return projectRoot ? (0, import_node_path.join)(projectRoot, LAUNCHSECURE_DIR) : (0, import_node_path.join)((0, import_node_os.homedir)(), LAUNCHSECURE_DIR);
}
function lockPath(projectRoot) {
  return (0, import_node_path.join)(lockDir(projectRoot), "launch-council.lock");
}
function setProjectRoot(root) {
  _activeProjectRoot = root;
}
function readLock(projectRoot) {
  const root = projectRoot ?? _activeProjectRoot;
  const p = lockPath(root);
  if (!(0, import_node_fs.existsSync)(p)) return null;
  try {
    const data = JSON.parse((0, import_node_fs.readFileSync)(p, "utf-8"));
    if (typeof data.pid !== "number" || typeof data.port !== "number") return null;
    return data;
  } catch {
    return null;
  }
}
function isPidAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
function getListenerPid(port) {
  try {
    const out = (0, import_node_child_process.execFileSync)("lsof", ["-nP", "-iTCP:" + port, "-sTCP:LISTEN", "-t"], {
      encoding: "utf-8",
      stdio: ["ignore", "pipe", "ignore"],
      timeout: 500
    }).trim();
    if (!out) return null;
    const pid = parseInt(out.split("\n")[0], 10);
    return Number.isFinite(pid) ? pid : null;
  } catch {
    return null;
  }
}
function getLiveLock(projectRoot) {
  const root = projectRoot ?? _activeProjectRoot;
  const lock = readLock(root);
  if (!lock) return null;
  const listenerPid = getListenerPid(lock.port);
  const live = listenerPid !== null ? listenerPid === lock.pid : isPidAlive(lock.pid);
  if (!live) {
    try {
      (0, import_node_fs.unlinkSync)(lockPath(root));
    } catch {
    }
    return null;
  }
  return lock;
}
function writeLock(data, projectRoot) {
  const root = projectRoot ?? _activeProjectRoot;
  (0, import_node_fs.mkdirSync)(lockDir(root), { recursive: true });
  (0, import_node_fs.writeFileSync)(lockPath(root), JSON.stringify(data, null, 2) + "\n", "utf-8");
  if (root) _activeProjectRoot = root;
}
function clearLock(projectRoot) {
  const root = projectRoot ?? _activeProjectRoot;
  try {
    (0, import_node_fs.unlinkSync)(lockPath(root));
  } catch {
  }
}
var import_node_child_process, import_node_fs, import_node_os, import_node_path, _activeProjectRoot;
var init_council_lockfile = __esm({
  "src/server/council-lockfile.ts"() {
    "use strict";
    import_node_child_process = require("node:child_process");
    import_node_fs = require("node:fs");
    import_node_os = require("node:os");
    import_node_path = require("node:path");
    init_launch_kit_paths();
  }
});

// src/server/council-config.ts
function loadCouncilConfig(rootDir) {
  const configPath = (0, import_node_path2.join)(rootDir, CONFIG_FILENAME);
  if (!(0, import_node_fs2.existsSync)(configPath)) return {};
  try {
    return JSON.parse((0, import_node_fs2.readFileSync)(configPath, "utf-8"));
  } catch {
    return {};
  }
}
function saveCouncilConfig(rootDir, config) {
  const configPath = (0, import_node_path2.join)(rootDir, CONFIG_FILENAME);
  (0, import_node_fs2.writeFileSync)(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
}
var import_node_fs2, import_node_path2, CONFIG_FILENAME;
var init_council_config = __esm({
  "src/server/council-config.ts"() {
    "use strict";
    import_node_fs2 = require("node:fs");
    import_node_path2 = require("node:path");
    CONFIG_FILENAME = ".launchcouncil.json";
  }
});

// src/server/mcp-client.ts
function loadMcpConfig(projectRoot) {
  if (_config) return _config;
  const mcpPath = (0, import_node_path3.join)(projectRoot, ".mcp.json");
  if (!(0, import_node_fs3.existsSync)(mcpPath)) {
    throw new Error(`.mcp.json not found at ${mcpPath}`);
  }
  const raw = JSON.parse((0, import_node_fs3.readFileSync)(mcpPath, "utf-8"));
  const entry = raw.mcpServers["launch-secure"];
  if (!entry?.url) {
    throw new Error('No "launch-secure" entry with url found in .mcp.json');
  }
  _config = {
    url: entry.url,
    headers: entry.headers ?? {}
  };
  return _config;
}
function parseSSE(text2) {
  const lines = text2.split("\n");
  for (const line of lines) {
    if (line.startsWith("data: ")) {
      const data = line.slice(6);
      try {
        return JSON.parse(data);
      } catch {
      }
    }
  }
  return JSON.parse(text2);
}
async function mcpRequest(method, params) {
  const config = _config;
  if (!config) throw new Error("MCP config not loaded \u2014 call loadMcpConfig first");
  const id = ++_requestId;
  const headers = {
    ...config.headers,
    "Content-Type": "application/json",
    "Accept": "application/json, text/event-stream"
  };
  if (_sessionId) {
    headers["Mcp-Session-Id"] = _sessionId;
  }
  const response = await fetch(config.url, {
    method: "POST",
    headers,
    body: JSON.stringify({ jsonrpc: "2.0", id, method, params })
  });
  const sid = response.headers.get("mcp-session-id");
  if (sid) _sessionId = sid;
  if (!response.ok) {
    const text2 = await response.text();
    throw new Error(`MCP ${method} failed (${response.status}): ${text2}`);
  }
  const contentType = response.headers.get("content-type") ?? "";
  const body = await response.text();
  if (contentType.includes("text/event-stream")) {
    return parseSSE(body);
  }
  return JSON.parse(body);
}
async function ensureInitialized() {
  if (_sessionId) return;
  await mcpRequest("initialize", {
    protocolVersion: "2024-11-05",
    capabilities: {},
    clientInfo: { name: "launch-council", version: "0.0.1" }
  });
  const config = _config;
  const headers = {
    ...config.headers,
    "Content-Type": "application/json",
    "Accept": "application/json, text/event-stream"
  };
  if (_sessionId) headers["Mcp-Session-Id"] = _sessionId;
  await fetch(config.url, {
    method: "POST",
    headers,
    body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
  });
}
async function callTool(toolName, args) {
  await ensureInitialized();
  const result = await mcpRequest("tools/call", {
    name: toolName,
    arguments: args
  });
  if (result.error) {
    throw new Error(`MCP tool error: ${result.error.message}`);
  }
  const textContent = result.result?.content?.[0]?.text;
  if (!textContent) return null;
  return JSON.parse(textContent);
}
async function readDiscussion(discussionId) {
  const result = await callTool("communication_read", {
    resource_type: "discussion",
    limit: 50
  });
  if (!result?.comments) return null;
  const discussion = result.comments.find((c) => c.id === discussionId);
  return discussion ?? null;
}
async function listDiscussions() {
  const result = await callTool("communication_read", {
    resource_type: "discussion",
    limit: 50
  });
  return result?.comments ?? [];
}
async function writeReply(parentId, body, title) {
  const result = await callTool("communication_write", {
    body,
    title: title ?? void 0,
    parent_id: parentId,
    resource_type: "comment"
  });
  return { id: result.created.id };
}
var import_node_fs3, import_node_path3, _config, _requestId, _sessionId;
var init_mcp_client = __esm({
  "src/server/mcp-client.ts"() {
    "use strict";
    import_node_fs3 = require("node:fs");
    import_node_path3 = require("node:path");
    _config = null;
    _requestId = 0;
    _sessionId = null;
  }
});

// src/server/personas.ts
function getCustomPersonas() {
  return Array.from(customPersonas.values());
}
function getAllPersonas() {
  return [...PRESET_PERSONAS, ...getCustomPersonas()];
}
function getPersona(id) {
  return PRESET_PERSONAS.find((p) => p.id === id) ?? customPersonas.get(id);
}
function addCustomPersona(name, style, systemPrompt) {
  const id = `custom-${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
  const persona = {
    id,
    name,
    style,
    systemPrompt: systemPrompt + COMMON_INSTRUCTIONS,
    isPreset: false
  };
  customPersonas.set(id, persona);
  return persona;
}
function removeCustomPersona(id) {
  return customPersonas.delete(id);
}
function setPersonaAIConfig(personaId, config) {
  personaAIConfigs.set(personaId, config);
}
function getPersonaAIConfig(personaId) {
  return personaAIConfigs.get(personaId);
}
function getAllPersonaAIConfigs() {
  return Object.fromEntries(personaAIConfigs);
}
var COMMON_INSTRUCTIONS, PRESET_PERSONAS, customPersonas, personaAIConfigs;
var init_personas = __esm({
  "src/server/personas.ts"() {
    "use strict";
    COMMON_INSTRUCTIONS = `

You are participating in a council discussion about a software project decision. You will be given:
1. The discussion topic and any replies so far
2. Relevant code context from the project

Be precise in answering and no explanation needed. State your position in 2-3 sentences max. No preamble, no lengthy analysis. Direct and to the point. Under 100 words.`;
    PRESET_PERSONAS = [
      {
        id: "frontend-lead",
        name: "Frontend Lead",
        style: "UX-first, component architecture, performance",
        isPreset: true,
        systemPrompt: `You are a senior Frontend Lead with deep expertise in React, TypeScript, component architecture, and user experience. You prioritize:
- Clean component boundaries and reusability
- User experience and interaction design
- Performance (bundle size, render cycles, lazy loading)
- Accessibility and responsive design
- State management clarity

When evaluating proposals, you think about how they affect the UI layer, whether components stay composable, and if the user experience degrades or improves.${COMMON_INSTRUCTIONS}`
      },
      {
        id: "backend-lead",
        name: "Backend Lead",
        style: "API design, data flow, scalability",
        isPreset: true,
        systemPrompt: `You are a senior Backend Lead with deep expertise in API design, server architecture, and distributed systems. You prioritize:
- Clean API contracts and versioning
- Data flow efficiency and caching strategy
- Error handling and resilience
- Scalability under load
- Security at the API boundary

When evaluating proposals, you think about server-side implications, API design, data consistency, and how changes affect the system's ability to scale.${COMMON_INSTRUCTIONS}`
      },
      {
        id: "db-lead",
        name: "Database Lead",
        style: "Schema integrity, query performance, migrations",
        isPreset: true,
        systemPrompt: `You are a senior Database Lead with deep expertise in schema design, query optimization, and data integrity. You prioritize:
- Schema normalization and referential integrity
- Query performance and index strategy
- Migration safety (zero-downtime, reversible)
- Data modeling that serves both read and write patterns
- Avoiding N+1 queries and unnecessary joins

When evaluating proposals, you think about how changes affect the data model, whether migrations are safe, and if queries will perform well at scale.${COMMON_INSTRUCTIONS}`
      },
      {
        id: "devils-advocate",
        name: "Devil's Advocate",
        style: "Challenges assumptions, finds holes",
        isPreset: true,
        systemPrompt: `You are the Devil's Advocate on this council. Your job is to stress-test ideas by actively challenging assumptions and finding weaknesses. You:
- Question the premise \u2014 is this even the right problem to solve?
- Find edge cases and failure modes others miss
- Challenge "obvious" solutions that might have hidden costs
- Ask what happens when things go wrong
- Point out what's being hand-waved or deferred

You are NOT negative for the sake of it. You genuinely want better outcomes, and you achieve that by making sure the group has considered the downsides before committing.${COMMON_INSTRUCTIONS}`
      },
      {
        id: "pragmatist",
        name: "Pragmatist",
        style: "Ship-first, scope reduction, trade-offs",
        isPreset: true,
        systemPrompt: `You are the Pragmatist on this council. You focus on shipping value quickly and reducing scope to what matters. You prioritize:
- What's the simplest thing that works?
- Can we ship a smaller version first and iterate?
- What's the effort-to-impact ratio?
- Are we over-engineering for hypothetical future needs?
- What can we defer without blocking progress?

You respect quality but reject gold-plating. You look for the 80/20 solution and advocate for incremental delivery over big-bang releases.${COMMON_INSTRUCTIONS}`
      },
      {
        id: "security-reviewer",
        name: "Security Reviewer",
        style: "Threat model, auth, input validation",
        isPreset: true,
        systemPrompt: `You are the Security Reviewer on this council. You evaluate proposals through a security lens. You focus on:
- Authentication and authorization gaps
- Input validation and injection risks (SQL, XSS, command injection)
- Data exposure and privacy concerns
- Secrets management and credential handling
- Attack surface changes \u2014 does this proposal increase exposure?

You think like an attacker: what would you exploit if this shipped as described? You provide specific, actionable security guidance, not generic warnings.${COMMON_INSTRUCTIONS}`
      }
    ];
    customPersonas = /* @__PURE__ */ new Map();
    personaAIConfigs = /* @__PURE__ */ new Map();
  }
});

// src/server/intent.ts
async function extractIntent(adapter, discussionContent) {
  const response = await adapter.complete(INTENT_SYSTEM_PROMPT, discussionContent);
  try {
    const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
    const parsed = JSON.parse(cleaned);
    return {
      summary: parsed.summary ?? "Could not extract summary",
      relevantAreas: Array.isArray(parsed.relevantAreas) ? parsed.relevantAreas : [],
      suggestedLayers: Array.isArray(parsed.suggestedLayers) ? parsed.suggestedLayers.filter((l) => ["ui", "api", "db"].includes(l)) : ["ui", "api", "db"]
    };
  } catch {
    return {
      summary: response.slice(0, 200),
      relevantAreas: [],
      suggestedLayers: ["ui", "api", "db"]
    };
  }
}
var INTENT_SYSTEM_PROMPT;
var init_intent = __esm({
  "src/server/intent.ts"() {
    "use strict";
    INTENT_SYSTEM_PROMPT = `You are a technical intent extractor. Given a discussion from a software project, you must:
1. Summarize what the discussion is about in 1-2 sentences.
2. Identify specific code areas that are relevant (component names, API endpoints, database tables, module names, feature names). These will be used as search terms against a code graph.
3. Suggest which layers of the codebase are relevant: "ui" (frontend components, pages, hooks), "api" (backend endpoints, server logic), "db" (database tables, schema).

Respond in JSON only, no markdown fences:
{
  "summary": "...",
  "relevantAreas": ["term1", "term2", ...],
  "suggestedLayers": ["ui", "api", "db"]
}

Be specific with search terms \u2014 use actual names that would appear in code (e.g. "auth", "login", "User", "pipeline", "dashboard"), not generic descriptions.`;
  }
});

// src/server/graph-reader.ts
function readGraphLayer(projectRoot, layer) {
  const filePath = (0, import_node_path4.join)(projectRoot, LAUNCHSECURE_DIR, GRAPHS_SUBDIR, `${layer}.json`);
  if (!(0, import_node_fs4.existsSync)(filePath)) return null;
  try {
    return JSON.parse((0, import_node_fs4.readFileSync)(filePath, "utf-8"));
  } catch {
    return null;
  }
}
function matchesSearch(node, terms) {
  const haystack = [node.i, node.n, node.m, node.r].filter(Boolean).join(" ").toLowerCase();
  return terms.some((term) => haystack.includes(term.toLowerCase()));
}
function formatNode(node, layer) {
  const parts = [`[${layer}/${node.t}] ${node.n}`];
  if (node.r) parts.push(`route: ${node.r}`);
  if (node.mt?.length) parts.push(`methods: ${node.mt.join(", ")}`);
  if (node.m) parts.push(`module: ${node.m}`);
  parts.push(`file: ${node.i}`);
  return parts.join(" | ");
}
function searchGraph(projectRoot, searchTerms, layers = ["ui", "api", "db"]) {
  if (searchTerms.length === 0) {
    return { summary: "No search terms provided \u2014 skipping graph context.", nodeCount: 0, layers: [] };
  }
  const results = [];
  const usedLayers = [];
  let totalNodes = 0;
  for (const layer of layers) {
    const graph = readGraphLayer(projectRoot, layer);
    if (!graph) continue;
    const matched = graph.nodes.filter((n) => matchesSearch(n, searchTerms));
    if (matched.length === 0) continue;
    usedLayers.push(layer);
    totalNodes += matched.length;
    results.push(`## ${layer.toUpperCase()} layer (${matched.length} nodes)`);
    const capped = matched.slice(0, 30);
    for (const node of capped) {
      results.push(`- ${formatNode(node, layer)}`);
    }
    if (matched.length > 30) {
      results.push(`  ... and ${matched.length - 30} more`);
    }
    results.push("");
  }
  if (results.length === 0) {
    return {
      summary: `No graph nodes matched search terms: ${searchTerms.join(", ")}`,
      nodeCount: 0,
      layers: []
    };
  }
  return {
    summary: results.join("\n"),
    nodeCount: totalNodes,
    layers: usedLayers
  };
}
var import_node_fs4, import_node_path4, GRAPHS_SUBDIR;
var init_graph_reader = __esm({
  "src/server/graph-reader.ts"() {
    "use strict";
    import_node_fs4 = require("node:fs");
    import_node_path4 = require("node:path");
    init_launch_kit_paths();
    GRAPHS_SUBDIR = "graphs";
  }
});

// src/server/adapters/claude-terminal.ts
var claude_terminal_exports = {};
__export(claude_terminal_exports, {
  ClaudeTerminalAdapter: () => ClaudeTerminalAdapter
});
var import_node_child_process2, ClaudeTerminalAdapter;
var init_claude_terminal = __esm({
  "src/server/adapters/claude-terminal.ts"() {
    "use strict";
    import_node_child_process2 = require("node:child_process");
    ClaudeTerminalAdapter = class {
      constructor(model) {
        this.model = model ?? "sonnet";
      }
      complete(systemPrompt, userPrompt) {
        return new Promise((resolve, reject) => {
          const combinedPrompt = `<INSTRUCTIONS>
${systemPrompt}
</INSTRUCTIONS>

${userPrompt}`;
          const args = [
            "-p",
            "-",
            "--model",
            this.model,
            "--output-format",
            "text"
          ];
          const proc = (0, import_node_child_process2.spawn)("claude", args, {
            stdio: ["pipe", "pipe", "pipe"],
            timeout: 18e4
          });
          proc.stdin.write(combinedPrompt);
          proc.stdin.end();
          let stdout = "";
          let stderr = "";
          proc.stdout.on("data", (chunk) => {
            stdout += chunk.toString();
          });
          proc.stderr.on("data", (chunk) => {
            stderr += chunk.toString();
          });
          proc.on("close", (code) => {
            if (code === 0) {
              resolve(stdout.trim());
            } else {
              reject(new Error(`claude exited with code ${code}: ${stderr.trim()}`));
            }
          });
          proc.on("error", (err) => {
            reject(new Error(`Failed to spawn claude: ${err.message}`));
          });
        });
      }
    };
  }
});

// src/server/adapters/openrouter.ts
var openrouter_exports = {};
__export(openrouter_exports, {
  OpenRouterAdapter: () => OpenRouterAdapter
});
var OpenRouterAdapter;
var init_openrouter = __esm({
  "src/server/adapters/openrouter.ts"() {
    "use strict";
    OpenRouterAdapter = class {
      constructor(config) {
        this.apiKey = config.apiKey;
        this.model = config.model;
        this.baseUrl = config.baseUrl ?? "https://openrouter.ai/api/v1";
      }
      async complete(systemPrompt, userPrompt) {
        const response = await fetch(`${this.baseUrl}/chat/completions`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${this.apiKey}`,
            "HTTP-Referer": "https://automatewith.us",
            "X-Title": "LaunchCouncil"
          },
          body: JSON.stringify({
            model: this.model,
            messages: [
              { role: "system", content: systemPrompt },
              { role: "user", content: userPrompt }
            ],
            max_tokens: 4096
          })
        });
        if (!response.ok) {
          const text2 = await response.text();
          throw new Error(`OpenRouter ${response.status}: ${text2}`);
        }
        const data = await response.json();
        const content = data.choices?.[0]?.message?.content;
        if (!content) throw new Error("Empty response from OpenRouter");
        return content;
      }
    };
  }
});

// src/server/adapters/types.ts
function createAdapter(config) {
  switch (config.provider) {
    case "claude-terminal": {
      const { ClaudeTerminalAdapter: ClaudeTerminalAdapter2 } = (init_claude_terminal(), __toCommonJS(claude_terminal_exports));
      return new ClaudeTerminalAdapter2(config.claudeTerminal?.model);
    }
    case "openrouter": {
      if (!config.openrouter) throw new Error("openrouter config required when provider is 'openrouter'");
      const { OpenRouterAdapter: OpenRouterAdapter2 } = (init_openrouter(), __toCommonJS(openrouter_exports));
      return new OpenRouterAdapter2(config.openrouter);
    }
    default:
      throw new Error(`Unknown provider: ${config.provider}`);
  }
}
var init_types = __esm({
  "src/server/adapters/types.ts"() {
    "use strict";
  }
});

// src/server/orchestrator.ts
function getSession(id) {
  return sessions.get(id);
}
function getAllSessions() {
  return Array.from(sessions.values());
}
function onSessionUpdate(fn) {
  listeners.push(fn);
  return () => {
    const idx = listeners.indexOf(fn);
    if (idx >= 0) listeners.splice(idx, 1);
  };
}
function emit(session) {
  for (const fn of listeners) fn(session);
}
function buildUserPrompt(discussion, intent, graphContext) {
  const parts = [];
  parts.push("# Discussion");
  if (discussion.title) parts.push(`**${discussion.title}**
`);
  parts.push(discussion.content);
  if (discussion.replies.length > 0) {
    parts.push("\n## Existing Replies");
    for (const reply of discussion.replies) {
      parts.push(`**${reply.author.name ?? "Unknown"}**: ${reply.content}`);
    }
  }
  parts.push(`
## Discussion Summary
${intent.summary}`);
  if (graphContext.nodeCount > 0) {
    parts.push(`
# Relevant Code Context
${graphContext.summary}`);
  }
  parts.push("\n---\nGive your perspective on this discussion based on your role and expertise.");
  return parts.join("\n");
}
async function summonCouncil(discussionId, personaIds, adapterConfig2, projectRoot) {
  const sessionId = `council-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  const personas = [];
  for (const id of personaIds) {
    const p = getPersona(id);
    if (!p) throw new Error(`Unknown persona: ${id}`);
    personas.push(p);
  }
  const session = {
    id: sessionId,
    discussionId,
    personaIds,
    status: "pending",
    step: "Initializing",
    results: [],
    startedAt: Date.now()
  };
  sessions.set(sessionId, session);
  emit(session);
  runCouncil(session, personas, adapterConfig2, projectRoot).catch((err) => {
    session.status = "error";
    session.error = String(err);
    session.step = "Failed";
    emit(session);
  });
  return sessionId;
}
async function runCouncil(session, personas, adapterConfig2, projectRoot) {
  const adapter = createAdapter(adapterConfig2);
  session.status = "reading";
  session.step = "Reading discussion from LaunchSecure";
  emit(session);
  const discussion = await readDiscussion(session.discussionId);
  if (!discussion) {
    throw new Error(`Discussion ${session.discussionId} not found`);
  }
  session.status = "extracting";
  session.step = "Extracting discussion intent";
  emit(session);
  const intent = await extractIntent(adapter, [
    discussion.title ?? "",
    discussion.content,
    ...discussion.replies.map((r) => r.content)
  ].join("\n\n"));
  session.intent = intent;
  emit(session);
  session.status = "gathering";
  session.step = `Searching code graph for: ${intent.relevantAreas.join(", ")}`;
  emit(session);
  const graphContext = searchGraph(projectRoot, intent.relevantAreas, intent.suggestedLayers);
  session.graphContext = graphContext;
  emit(session);
  session.status = "deliberating";
  session.step = `Council deliberating (${personas.length} personas)`;
  emit(session);
  const userPrompt = buildUserPrompt(discussion, intent, graphContext);
  const pending = personas.map(async (persona) => {
    const start = Date.now();
    const personaOverride = getPersonaAIConfig(persona.id);
    const personaAdapter = personaOverride?.provider ? createAdapter({
      provider: personaOverride.provider,
      claudeTerminal: personaOverride.provider === "claude-terminal" ? { model: personaOverride.model } : void 0,
      openrouter: personaOverride.provider === "openrouter" ? { apiKey: adapterConfig2.openrouter?.apiKey ?? "", model: personaOverride.model ?? "anthropic/claude-sonnet-4" } : void 0
    }) : personaOverride?.model ? createAdapter({ ...adapterConfig2, claudeTerminal: { model: personaOverride.model } }) : adapter;
    let result;
    try {
      const response = await personaAdapter.complete(persona.systemPrompt, userPrompt);
      result = { personaId: persona.id, personaName: persona.name, response, durationMs: Date.now() - start };
    } catch (err) {
      result = { personaId: persona.id, personaName: persona.name, response: "", error: String(err), durationMs: Date.now() - start };
    }
    session.results.push(result);
    session.step = `Council deliberating (${session.results.length}/${personas.length} done)`;
    emit(session);
  });
  await Promise.all(pending);
  session.status = "done";
  session.step = "Council complete";
  session.completedAt = Date.now();
  emit(session);
}
var sessions, listeners;
var init_orchestrator = __esm({
  "src/server/orchestrator.ts"() {
    "use strict";
    init_mcp_client();
    init_intent();
    init_graph_reader();
    init_personas();
    init_types();
    sessions = /* @__PURE__ */ new Map();
    listeners = [];
  }
});

// src/server/council-serve.ts
var council_serve_exports = {};
__export(council_serve_exports, {
  runServeCli: () => runServeCli,
  startCouncilServer: () => startCouncilServer
});
function loadAdapterFromDisk() {
  const fileConfig = loadCouncilConfig(configRootDir);
  return fileConfig.adapter ?? { provider: "claude-terminal", claudeTerminal: { model: "sonnet" } };
}
function broadcastToClients(message) {
  if (!wss) return;
  const data = JSON.stringify(message);
  for (const client of wss.clients) {
    if (client.readyState === import_ws.WebSocket.OPEN) {
      client.send(data);
    }
  }
}
function serveStatic(res, filePath) {
  if (!import_node_fs5.default.existsSync(filePath) || !import_node_fs5.default.statSync(filePath).isFile()) return false;
  const ext = import_node_path5.default.extname(filePath).toLowerCase();
  const mime = MIME_TYPES[ext] ?? "application/octet-stream";
  res.writeHead(200, { "Content-Type": mime, "Cache-Control": "no-cache" });
  import_node_fs5.default.createReadStream(filePath).pipe(res);
  return true;
}
function serveIndex(res, clientDir) {
  const indexPath = import_node_path5.default.join(clientDir, "index.html");
  if (!import_node_fs5.default.existsSync(indexPath)) {
    res.writeHead(500, { "Content-Type": "text/plain" });
    res.end(`LaunchCouncil client bundle not found at ${clientDir}. Run 'npm run build:client'.`);
    return;
  }
  serveStatic(res, indexPath);
}
function readBody(req) {
  return new Promise((resolve) => {
    let body = "";
    req.on("data", (chunk) => {
      body += chunk.toString();
    });
    req.on("end", () => resolve(body));
  });
}
function jsonResponse(res, status, data) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
}
function tryListen(server, port) {
  return new Promise((resolve, reject) => {
    const onError = (err) => {
      server.off("listening", onListening);
      reject(err);
    };
    const onListening = () => {
      server.off("error", onError);
      resolve(port);
    };
    server.once("error", onError);
    server.once("listening", onListening);
    server.listen(port, "127.0.0.1");
  });
}
async function bindWithFallback(server, startPort) {
  let lastErr = null;
  for (let i = 0; i < MAX_PORT_SCAN; i++) {
    try {
      return await tryListen(server, startPort + i);
    } catch (err) {
      if (err.code === "EADDRINUSE") {
        lastErr = err;
        continue;
      }
      throw err;
    }
  }
  throw lastErr ?? new Error("Failed to bind any port");
}
async function startCouncilServer(opts = {}) {
  const cwd = opts.cwd ?? process.cwd();
  const existing = getLiveLock(cwd);
  if (existing) {
    if (!opts.quiet) process.stderr.write(`[launch-council] already running (pid ${existing.pid}) at ${existing.url}
`);
    return { port: existing.port, url: existing.url };
  }
  try {
    loadMcpConfig(cwd);
  } catch (err) {
    process.stderr.write(`[launch-council] warning: ${err}
`);
  }
  const clientDir = opts.clientDir ?? import_node_path5.default.join(__dirname, "..", "council-client");
  onSessionUpdate((session) => {
    broadcastToClients({ type: "session_update", session });
  });
  const server = import_node_http.default.createServer(async (req, res) => {
    try {
      const url2 = new URL(req.url ?? "/", `http://${req.headers.host}`);
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
      res.setHeader("Access-Control-Allow-Headers", "Content-Type");
      if (req.method === "OPTIONS") {
        res.writeHead(204);
        res.end();
        return;
      }
      if (req.method === "GET" && url2.pathname === "/api/health") {
        jsonResponse(res, 200, { ok: true, tool: "launch-council" });
        return;
      }
      if (req.method === "POST" && url2.pathname === "/api/council/summon") {
        const body = JSON.parse(await readBody(req));
        if (!body.discussionId || !body.personas?.length) {
          jsonResponse(res, 400, { error: "discussionId and personas[] required" });
          return;
        }
        try {
          const config = body.adapterConfig ?? adapterConfig;
          const sessionId = await summonCouncil(body.discussionId, body.personas, config, cwd);
          jsonResponse(res, 200, { sessionId });
        } catch (err) {
          jsonResponse(res, 400, { error: String(err) });
        }
        return;
      }
      if (req.method === "GET" && url2.pathname.startsWith("/api/council/status/")) {
        const sessionId = url2.pathname.slice("/api/council/status/".length);
        const session = getSession(sessionId);
        if (!session) {
          jsonResponse(res, 404, { error: "Session not found" });
          return;
        }
        jsonResponse(res, 200, session);
        return;
      }
      if (req.method === "GET" && url2.pathname === "/api/council/sessions") {
        jsonResponse(res, 200, { sessions: getAllSessions() });
        return;
      }
      if (req.method === "GET" && url2.pathname === "/api/council/personas") {
        jsonResponse(res, 200, { personas: getAllPersonas() });
        return;
      }
      if (req.method === "POST" && url2.pathname === "/api/council/personas") {
        const body = JSON.parse(await readBody(req));
        if (!body.name || !body.systemPrompt) {
          jsonResponse(res, 400, { error: "name and systemPrompt required" });
          return;
        }
        const persona = addCustomPersona(body.name, body.style ?? "", body.systemPrompt);
        jsonResponse(res, 200, { persona });
        return;
      }
      if (req.method === "DELETE" && url2.pathname.startsWith("/api/council/personas/")) {
        const id = url2.pathname.slice("/api/council/personas/".length);
        const removed = removeCustomPersona(id);
        jsonResponse(res, 200, { removed });
        return;
      }
      if (req.method === "POST" && url2.pathname === "/api/council/persona-ai-config") {
        const body = JSON.parse(await readBody(req));
        if (!body.personaId) {
          jsonResponse(res, 400, { error: "personaId required" });
          return;
        }
        setPersonaAIConfig(body.personaId, body.config ?? {});
        jsonResponse(res, 200, { ok: true, personaId: body.personaId, config: body.config });
        return;
      }
      if (req.method === "GET" && url2.pathname === "/api/council/persona-ai-configs") {
        jsonResponse(res, 200, { configs: getAllPersonaAIConfigs() });
        return;
      }
      if (req.method === "GET" && url2.pathname === "/api/council/discussions") {
        try {
          const discussions = await listDiscussions();
          jsonResponse(res, 200, { discussions });
        } catch (err) {
          jsonResponse(res, 500, { error: `Failed to fetch discussions: ${err}` });
        }
        return;
      }
      if (req.method === "POST" && url2.pathname === "/api/council/post-response") {
        const body = JSON.parse(await readBody(req));
        if (!body.sessionId || !body.personaId) {
          jsonResponse(res, 400, { error: "sessionId and personaId required" });
          return;
        }
        const session = getSession(body.sessionId);
        if (!session) {
          jsonResponse(res, 404, { error: "Session not found" });
          return;
        }
        const result = session.results.find((r) => r.personaId === body.personaId);
        if (!result || !result.response) {
          jsonResponse(res, 400, { error: "No response found for this persona" });
          return;
        }
        if (result.replyId) {
          jsonResponse(res, 400, { error: "Already posted" });
          return;
        }
        try {
          const replyBody = `**[${result.personaName}]**

${result.response}`;
          const reply = await writeReply(session.discussionId, replyBody, `Council: ${result.personaName}`);
          result.replyId = reply.id;
          jsonResponse(res, 200, { ok: true, replyId: reply.id });
        } catch (err) {
          jsonResponse(res, 500, { error: `Failed to post: ${err}` });
        }
        return;
      }
      if (req.method === "GET" && url2.pathname === "/api/council/config") {
        const safe = {
          ...adapterConfig,
          openrouter: adapterConfig.openrouter ? { ...adapterConfig.openrouter, apiKey: adapterConfig.openrouter.apiKey ? "***" : "" } : void 0
        };
        jsonResponse(res, 200, { config: safe });
        return;
      }
      if (req.method === "POST" && url2.pathname === "/api/council/config") {
        const body = JSON.parse(await readBody(req));
        adapterConfig = { ...adapterConfig, ...body };
        const existing2 = loadCouncilConfig(configRootDir);
        existing2.adapter = adapterConfig;
        saveCouncilConfig(configRootDir, existing2);
        jsonResponse(res, 200, { ok: true, config: { ...adapterConfig, openrouter: adapterConfig.openrouter ? { ...adapterConfig.openrouter, apiKey: "***" } : void 0 } });
        return;
      }
      if (url2.pathname !== "/") {
        const staticPath = import_node_path5.default.join(clientDir, url2.pathname);
        if (serveStatic(res, staticPath)) return;
      }
      serveIndex(res, clientDir);
    } catch (err) {
      jsonResponse(res, 500, { error: String(err) });
    }
  });
  wss = new import_ws.WebSocketServer({ server });
  wss.on("connection", (ws) => {
    if (!opts.quiet) process.stderr.write("[launch-council] browser connected\n");
    ws.on("close", () => {
      if (!opts.quiet) process.stderr.write("[launch-council] browser disconnected\n");
    });
  });
  configRootDir = cwd;
  adapterConfig = loadAdapterFromDisk();
  const councilConfig = loadCouncilConfig(cwd);
  const startPort = opts.port ?? councilConfig.port ?? DEFAULT_PORT;
  const port = await bindWithFallback(server, startPort);
  const url = `http://localhost:${port}`;
  writeLock({ pid: process.pid, port, cwd, url, startedAt: (/* @__PURE__ */ new Date()).toISOString() }, cwd);
  const cleanup = () => {
    clearLock(cwd);
    server.close();
  };
  process.once("SIGINT", () => {
    cleanup();
    process.exit(0);
  });
  process.once("SIGTERM", () => {
    cleanup();
    process.exit(0);
  });
  process.once("exit", cleanup);
  if (!opts.quiet) process.stderr.write(`[launch-council] serving ${url}
`);
  return { port, url };
}
function runServeCli(argv) {
  let port;
  for (let i = 0; i < argv.length; i++) {
    if (argv[i] === "--port" && argv[i + 1]) {
      port = parseInt(argv[++i], 10);
    } else if (argv[i].startsWith("--port=")) {
      port = parseInt(argv[i].slice("--port=".length), 10);
    }
  }
  startCouncilServer({ port }).catch((err) => {
    process.stderr.write(`[launch-council] failed to start: ${err}
`);
    process.exit(1);
  });
}
var import_node_http, import_node_fs5, import_node_path5, import_ws, DEFAULT_PORT, MAX_PORT_SCAN, MIME_TYPES, configRootDir, adapterConfig, wss;
var init_council_serve = __esm({
  "src/server/council-serve.ts"() {
    "use strict";
    import_node_http = __toESM(require("node:http"));
    import_node_fs5 = __toESM(require("node:fs"));
    import_node_path5 = __toESM(require("node:path"));
    import_ws = require("ws");
    init_council_lockfile();
    init_council_config();
    init_mcp_client();
    init_personas();
    init_orchestrator();
    init_mcp_client();
    DEFAULT_PORT = 52839;
    MAX_PORT_SCAN = 3;
    MIME_TYPES = {
      ".html": "text/html; charset=utf-8",
      ".js": "application/javascript; charset=utf-8",
      ".css": "text/css; charset=utf-8",
      ".json": "application/json; charset=utf-8",
      ".png": "image/png",
      ".svg": "image/svg+xml",
      ".ico": "image/x-icon"
    };
    configRootDir = process.cwd();
    adapterConfig = {
      provider: "claude-terminal",
      claudeTerminal: { model: "sonnet" }
    };
    wss = null;
  }
});

// src/server/council-mcp.ts
var council_mcp_exports = {};
__export(council_mcp_exports, {
  startCouncilMcpServer: () => startCouncilMcpServer
});
function httpGet(url) {
  return new Promise((resolve, reject) => {
    const parsed = new URL(url);
    const req = import_node_http2.default.request(
      { hostname: parsed.hostname, port: parsed.port, path: parsed.pathname, method: "GET" },
      (res) => {
        let buf = "";
        res.on("data", (chunk) => {
          buf += chunk;
        });
        res.on("end", () => resolve(buf));
      }
    );
    req.on("error", reject);
    req.end();
  });
}
function httpPost(url, body) {
  return new Promise((resolve, reject) => {
    const data = JSON.stringify(body);
    const parsed = new URL(url);
    const req = import_node_http2.default.request(
      {
        hostname: parsed.hostname,
        port: parsed.port,
        path: parsed.pathname,
        method: "POST",
        headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) }
      },
      (res) => {
        let buf = "";
        res.on("data", (chunk) => {
          buf += chunk;
        });
        res.on("end", () => resolve(buf));
      }
    );
    req.on("error", reject);
    req.write(data);
    req.end();
  });
}
async function handleTool(name, args) {
  const projectRoot = process.cwd();
  switch (name) {
    case "summon_council": {
      const lock = getLiveLock(projectRoot);
      if (!lock) return text("LaunchCouncil server is not running. Call start_council_server first.");
      const response = await httpPost(`${lock.url}/api/council/summon`, {
        discussionId: args.discussionId,
        personas: args.personas
      });
      return text(response);
    }
    case "council_status": {
      const lock = getLiveLock(projectRoot);
      if (!lock) return text("LaunchCouncil server is not running.");
      const response = await httpGet(`${lock.url}/api/council/status/${args.sessionId}`);
      return text(response);
    }
    case "list_personas": {
      const lock = getLiveLock(projectRoot);
      if (!lock) return text("LaunchCouncil server is not running.");
      const response = await httpGet(`${lock.url}/api/council/personas`);
      return text(response);
    }
    case "list_discussions": {
      const lock = getLiveLock(projectRoot);
      if (!lock) return text("LaunchCouncil server is not running.");
      const response = await httpGet(`${lock.url}/api/council/discussions`);
      return text(response);
    }
    case "start_council_server": {
      const existing = getLiveLock(projectRoot);
      if (existing) {
        return text(JSON.stringify({
          running: true,
          url: existing.url,
          port: existing.port,
          pid: existing.pid,
          message: "LaunchCouncil is already running."
        }));
      }
      try {
        const logDir = (0, import_node_path6.join)((0, import_node_os2.homedir)(), LAUNCHSECURE_DIR);
        (0, import_node_fs6.mkdirSync)(logDir, { recursive: true });
        const logPath = (0, import_node_path6.join)(logDir, "launch-council.log");
        const out = (0, import_node_fs6.openSync)(logPath, "a");
        const err = (0, import_node_fs6.openSync)(logPath, "a");
        const entryPath = process.argv[1];
        const config = loadCouncilConfig(projectRoot);
        const resolvedPort = args.port ?? config.port;
        const portArg = resolvedPort ? ["--port", String(resolvedPort)] : [];
        const child = (0, import_node_child_process3.spawn)(process.execPath, [entryPath, "serve", ...portArg], {
          detached: true,
          stdio: ["ignore", out, err],
          env: { ...process.env }
        });
        child.unref();
        await new Promise((r) => setTimeout(r, 1e3));
        const lock = getLiveLock(projectRoot);
        if (lock) {
          return text(JSON.stringify({ running: true, url: lock.url, port: lock.port, pid: lock.pid }));
        }
        return text(JSON.stringify({
          running: false,
          message: `Server spawned (pid ${child.pid}) but lock not yet written. Check ~/.launchsecure/launch-council.log`
        }));
      } catch (err) {
        return text(JSON.stringify({ running: false, error: String(err) }));
      }
    }
    case "stop_council_server": {
      const lock = getLiveLock(projectRoot);
      if (!lock) return text(JSON.stringify({ ok: true, message: "No server running." }));
      try {
        process.kill(lock.pid, "SIGTERM");
      } catch {
      }
      clearLock(projectRoot);
      return text(JSON.stringify({ ok: true, message: `Stopped server (pid ${lock.pid}).` }));
    }
    case "council_server_status": {
      const lock = getLiveLock(projectRoot);
      if (lock) {
        return text(JSON.stringify({
          running: true,
          url: lock.url,
          port: lock.port,
          pid: lock.pid,
          startedAt: lock.startedAt
        }));
      }
      return text(JSON.stringify({ running: false }));
    }
    default:
      return text(`Unknown tool: ${name}`);
  }
}
function text(t) {
  return { content: [{ type: "text", text: t }] };
}
function send(msg) {
  process.stdout.write(JSON.stringify(msg) + "\n");
}
function sendResponse(id, result) {
  send({ jsonrpc: "2.0", id, result });
}
function sendError(id, code, message) {
  send({ jsonrpc: "2.0", id, error: { code, message } });
}
async function handleMessage(parsed) {
  const id = parsed.id;
  const method = parsed.method;
  const params = parsed.params ?? {};
  switch (method) {
    case "initialize":
      sendResponse(id, {
        protocolVersion: "2024-11-05",
        capabilities: { tools: {} },
        serverInfo: SERVER_INFO
      });
      break;
    case "notifications/initialized":
      break;
    case "tools/list":
      sendResponse(id, { tools: TOOLS });
      break;
    case "tools/call": {
      const toolName = params.name;
      const toolArgs = params.arguments ?? {};
      try {
        const result = await handleTool(toolName, toolArgs);
        sendResponse(id, result);
      } catch (err) {
        sendError(id, -32603, `Tool error: ${err}`);
      }
      break;
    }
    case "ping":
      sendResponse(id, {});
      break;
    default:
      if (id !== void 0) {
        sendError(id, -32601, `Method not found: ${method}`);
      }
  }
}
function startCouncilMcpServer() {
  process.stderr.write("[launch-council] MCP server starting on stdio\n");
  process.stdin.setEncoding("utf-8");
  let buffer = "";
  process.stdin.on("data", (chunk) => {
    buffer += chunk;
    const lines = buffer.split("\n");
    buffer = lines.pop() || "";
    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed) continue;
      try {
        handleMessage(JSON.parse(trimmed)).catch((err) => {
          process.stderr.write(`[launch-council] message error: ${err}
`);
        });
      } catch (err) {
        process.stderr.write(`[launch-council] parse error: ${err}
`);
      }
    }
  });
  process.stdin.on("end", () => {
    process.stderr.write("[launch-council] stdin closed, exiting\n");
    process.exit(0);
  });
}
var import_node_http2, import_node_path6, import_node_child_process3, import_node_fs6, import_node_os2, SERVER_INFO, TOOLS;
var init_council_mcp = __esm({
  "src/server/council-mcp.ts"() {
    "use strict";
    import_node_http2 = __toESM(require("node:http"));
    import_node_path6 = require("node:path");
    import_node_child_process3 = require("node:child_process");
    import_node_fs6 = require("node:fs");
    import_node_os2 = require("node:os");
    init_launch_kit_paths();
    init_council_lockfile();
    init_council_config();
    SERVER_INFO = {
      name: "launch-council",
      version: "0.0.1"
    };
    TOOLS = [
      {
        name: "summon_council",
        description: "Summon an AI council on a specific discussion. Spawns multiple personas to deliberate and posts their responses as replies to the discussion.\n\nRequires the council server to be running (call start_council_server first).",
        inputSchema: {
          type: "object",
          properties: {
            discussionId: {
              type: "string",
              description: "The discussion ID to deliberate on."
            },
            personas: {
              type: "array",
              items: { type: "string" },
              description: 'Persona IDs to include (e.g. ["frontend-lead", "devils-advocate"]). Call list_personas to see available options.'
            }
          },
          required: ["discussionId", "personas"]
        }
      },
      {
        name: "council_status",
        description: "Check the status of a council session by session ID.",
        inputSchema: {
          type: "object",
          properties: {
            sessionId: { type: "string", description: "The session ID returned by summon_council." }
          },
          required: ["sessionId"]
        }
      },
      {
        name: "list_personas",
        description: "List all available council personas (presets + custom).",
        inputSchema: { type: "object", properties: {} }
      },
      {
        name: "list_discussions",
        description: "List recent discussions from the LaunchSecure Communication Center.",
        inputSchema: { type: "object", properties: {} }
      },
      {
        name: "start_council_server",
        description: "Start the LaunchCouncil server. Returns the URL.",
        inputSchema: {
          type: "object",
          properties: {
            port: { type: "number", description: "Port to bind (default 52839)" }
          }
        }
      },
      {
        name: "stop_council_server",
        description: "Stop the running LaunchCouncil server.",
        inputSchema: { type: "object", properties: {} }
      },
      {
        name: "council_server_status",
        description: "Check whether the LaunchCouncil server is running.",
        inputSchema: { type: "object", properties: {} }
      }
    ];
  }
});

// src/server/council-entry.ts
init_council_lockfile();
async function main() {
  setProjectRoot(process.cwd());
  const argv = process.argv.slice(2);
  const subcommand = argv[0];
  if (subcommand === "serve") {
    const { runServeCli: runServeCli2 } = await Promise.resolve().then(() => (init_council_serve(), council_serve_exports));
    runServeCli2(argv.slice(1));
    return;
  }
  const { startCouncilMcpServer: startCouncilMcpServer2 } = await Promise.resolve().then(() => (init_council_mcp(), council_mcp_exports));
  startCouncilMcpServer2();
}
main().catch((err) => {
  process.stderr.write(`[launch-council] fatal: ${err}
`);
  process.exit(1);
});
