#!/usr/bin/env node

// dist/index.js
import { Command } from "commander";

// dist/commands/install.js
import { readFile, writeFile } from "fs/promises";
import { existsSync } from "fs";
import { join } from "path";
import { homedir } from "os";
function expandPath(p) {
  if (p.startsWith("~")) {
    return join(homedir(), p.slice(1));
  }
  if (p.startsWith("%APPDATA%")) {
    const appData = process.env.APPDATA || join(homedir(), "AppData", "Roaming");
    return join(appData, p.slice("%APPDATA%".length));
  }
  return p;
}
var AGENT_CONFIGS = [
  { name: "Claude Code", path: "~/.claude/claude_desktop_config.json", format: "claude" },
  { name: "Claude Code (Windows)", path: "%APPDATA%/Claude/claude_desktop_config.json", format: "claude" },
  { name: "Gemini CLI", path: "~/.gemini/settings.json", format: "gemini" },
  { name: "Cursor", path: "~/.cursor/mcp.json", format: "cursor" },
  { name: "Windsurf", path: "~/.codeium/windsurf/mcp_config.json", format: "cursor" }
];
var MCP_ENTRY = {
  command: "npx",
  args: ["-y", "vibe-splain", "serve"]
};
async function installCommand() {
  console.error("\n\u{1F527} VIBE-SPLAIN Installer\n");
  let patchedCount = 0;
  for (const agent of AGENT_CONFIGS) {
    const resolvedPath = expandPath(agent.path);
    if (!existsSync(resolvedPath)) {
      continue;
    }
    console.error(`  Found ${agent.name} config at ${resolvedPath}`);
    try {
      const raw = await readFile(resolvedPath, "utf8");
      let config;
      try {
        config = JSON.parse(raw);
      } catch {
        console.error(`    \u26A0 Could not parse JSON, skipping`);
        continue;
      }
      if (config.mcpServers?.["vibe-splain"]) {
        console.error(`    \u2713 Already configured, skipping`);
        patchedCount++;
        continue;
      }
      if (!config.mcpServers) {
        config.mcpServers = {};
      }
      config.mcpServers["vibe-splain"] = MCP_ENTRY;
      await writeFile(resolvedPath, JSON.stringify(config, null, 2), "utf8");
      console.error(`    \u2705 Patched successfully`);
      patchedCount++;
    } catch (err) {
      console.error(`    \u274C Error patching: ${err}`);
    }
  }
  if (patchedCount === 0) {
    console.error(`
\u26A0\uFE0F  No supported coding agent config found.`);
    console.error(`Add this manually to your agent's MCP config:
`);
    console.error(JSON.stringify({
      mcpServers: {
        "vibe-splain": MCP_ENTRY
      }
    }, null, 2));
    process.exit(1);
  } else {
    console.error(`
\u2705 Patched ${patchedCount} agent config(s). Restart your coding agent to activate.
`);
  }
}

// dist/mcp/server.js
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";

// ../brain/dist/scanner.js
import Parser from "web-tree-sitter";
import { join as join3, dirname, relative, extname } from "path";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import { readFile as readFile3, readdir } from "fs/promises";
import { existsSync as existsSync2 } from "fs";

// ../brain/dist/graph.js
import { join as join2 } from "path";
import { readFile as readFile2, writeFile as writeFile2, mkdir } from "fs/promises";
async function readGraph(projectRoot) {
  const graphPath = join2(projectRoot, ".vibe-splainer", "graph.json");
  try {
    const raw = await readFile2(graphPath, "utf8");
    return JSON.parse(raw);
  } catch {
    return null;
  }
}
async function writeGraph(projectRoot, graph) {
  const dir = join2(projectRoot, ".vibe-splainer");
  await mkdir(dir, { recursive: true });
  const graphPath = join2(dir, "graph.json");
  await writeFile2(graphPath, JSON.stringify(graph, null, 2), "utf8");
}

// ../brain/dist/scanner.js
var __dirname = dirname(fileURLToPath(import.meta.url));
var require2 = createRequire(import.meta.url);
var parser = null;
async function initParser() {
  if (parser)
    return parser;
  await Parser.init();
  parser = new Parser();
  let wasmPath;
  try {
    const wasmsDir = dirname(require2.resolve("tree-sitter-wasms/package.json"));
    wasmPath = join3(wasmsDir, "out", "tree-sitter-typescript.wasm");
    if (!existsSync2(wasmPath))
      throw new Error("WASM not found in package");
  } catch {
    wasmPath = join3(__dirname, "../wasm", "tree-sitter-typescript.wasm");
  }
  const Lang = await Parser.Language.load(wasmPath);
  parser.setLanguage(Lang);
  return parser;
}
var EXCLUDE_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".next", ".vibe-splainer", ".git"]);
var EXCLUDE_PATTERNS = [/\.test\./, /\.spec\./, /\.config\./, /\.lock$/, /\.min\.js$/, /\.d\.ts$/];
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx"]);
var PILLAR_KEYWORDS = {
  "Auth": ["passport", "jsonwebtoken", "bcrypt", "oauth", "session", "cookie-parser"],
  "Database": ["prisma", "mongoose", "sequelize", "typeorm", "knex", "pg", "mysql2"],
  "Payments": ["stripe", "paypal", "braintree", "plaid"],
  "Routing": ["express.Router", "fastify", "koa-router", "next/router"],
  "Queue": ["bull", "bullmq", "amqplib", "kafka", "redis"],
  "Storage": ["aws-sdk", "s3", "multer", "cloudinary", "@google-cloud/storage"],
  "Config": ["dotenv", "convict", "zod"]
};
async function collectFiles(dir, projectRoot) {
  const files = [];
  const entries = await readdir(dir, { withFileTypes: true });
  for (const entry of entries) {
    if (EXCLUDE_DIRS.has(entry.name))
      continue;
    const fullPath = join3(dir, entry.name);
    if (entry.isDirectory()) {
      const subFiles = await collectFiles(fullPath, projectRoot);
      files.push(...subFiles);
    } else if (entry.isFile()) {
      const ext = extname(entry.name);
      if (!SUPPORTED_EXTENSIONS.has(ext))
        continue;
      const relPath = relative(projectRoot, fullPath);
      if (EXCLUDE_PATTERNS.some((p) => p.test(relPath)))
        continue;
      files.push(fullPath);
    }
  }
  return files;
}
function detectPillars(source) {
  const pillars = [];
  for (const [pillar, keywords] of Object.entries(PILLAR_KEYWORDS)) {
    for (const kw of keywords) {
      if (source.includes(kw)) {
        if (!pillars.includes(pillar))
          pillars.push(pillar);
        break;
      }
    }
  }
  return pillars;
}
function computeNestingDepth(node, depth = 0) {
  let maxDepth = depth;
  const nestingTypes = /* @__PURE__ */ new Set([
    "function_declaration",
    "function",
    "arrow_function",
    "method_definition",
    "class_declaration",
    "class",
    "if_statement",
    "for_statement",
    "for_in_statement",
    "while_statement",
    "do_statement",
    "switch_statement",
    "try_statement",
    "catch_clause"
  ]);
  for (const child of node.children) {
    if (nestingTypes.has(child.type)) {
      const childMax = computeNestingDepth(child, depth + 1);
      maxDepth = Math.max(maxDepth, childMax);
    } else {
      const childMax = computeNestingDepth(child, depth);
      maxDepth = Math.max(maxDepth, childMax);
    }
  }
  return maxDepth;
}
function countMutations(node) {
  let count = 0;
  if (node.type === "assignment_expression" || node.type === "augmented_assignment_expression") {
    const parent = node.parent;
    if (!parent || parent.type !== "variable_declarator" || !parent.parent || parent.parent.type !== "lexical_declaration" || parent.parent.children[0]?.text !== "const") {
      count++;
    }
  }
  for (const child of node.children) {
    count += countMutations(child);
  }
  return count;
}
function countImports(node) {
  let count = 0;
  for (const child of node.children) {
    if (child.type === "import_statement" || child.type === "import_declaration") {
      count++;
    }
  }
  return count;
}
function extractImportPaths(source) {
  const paths = [];
  const importRegex = /(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;
  let match;
  while ((match = importRegex.exec(source)) !== null) {
    paths.push(match[1]);
  }
  return paths;
}
async function scanProject(projectRoot) {
  const p = await initParser();
  const files = await collectFiles(projectRoot, projectRoot);
  const graph = { nodes: {}, edges: [] };
  const fileImportMap = /* @__PURE__ */ new Map();
  const reverseImportCount = /* @__PURE__ */ new Map();
  for (const file of files) {
    const source = await readFile3(file, "utf8");
    const relPath = relative(projectRoot, file);
    const importPaths = extractImportPaths(source);
    fileImportMap.set(file, importPaths);
    graph.nodes[relPath] = { imports: importPaths };
    for (const imp of importPaths) {
      if (imp.startsWith(".")) {
        const resolvedDir = dirname(file);
        const resolved = join3(resolvedDir, imp);
        for (const ext of [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js"]) {
          const candidate = resolved.endsWith(ext) ? resolved : resolved + ext;
          const relCandidate = relative(projectRoot, candidate);
          reverseImportCount.set(relCandidate, (reverseImportCount.get(relCandidate) || 0) + 1);
        }
      }
    }
  }
  const allAnalyzed = [];
  for (const file of files) {
    const source = await readFile3(file, "utf8");
    const relPath = relative(projectRoot, file);
    const pillars = detectPillars(source);
    let tree;
    try {
      tree = p.parse(source);
    } catch {
      continue;
    }
    const importCount = countImports(tree.rootNode);
    const reverseCount = reverseImportCount.get(relPath) || 0;
    const linkDensity = importCount + reverseCount;
    const nestingDepth = computeNestingDepth(tree.rootNode);
    const mutationCount = countMutations(tree.rootNode);
    const cognitiveWeight = linkDensity * 2 + nestingDepth + mutationCount * 1.5;
    const importPaths = fileImportMap.get(file) || [];
    for (const imp of importPaths) {
      graph.edges.push({ from: relPath, to: imp });
    }
    allAnalyzed.push({
      path: file,
      relativePath: relPath,
      cognitiveWeight,
      linkDensity,
      nestingDepth,
      mutationCount,
      pillars
    });
  }
  const highGravityFiles = allAnalyzed.filter((f) => f.cognitiveWeight >= 15).sort((a, b) => b.cognitiveWeight - a.cognitiveWeight);
  const pillarMap = /* @__PURE__ */ new Map();
  const untaggedFiles = [];
  for (const file of highGravityFiles) {
    if (file.pillars.length > 0) {
      for (const pillar of file.pillars) {
        if (!pillarMap.has(pillar))
          pillarMap.set(pillar, []);
        pillarMap.get(pillar).push(file);
      }
    } else {
      untaggedFiles.push(file);
    }
  }
  const dirGroups = /* @__PURE__ */ new Map();
  for (const file of untaggedFiles) {
    const dir = dirname(file.relativePath);
    if (!dirGroups.has(dir))
      dirGroups.set(dir, []);
    dirGroups.get(dir).push(file);
  }
  const pillarGroups = [];
  for (const [name, files2] of pillarMap) {
    pillarGroups.push({ name, files: files2 });
  }
  for (const [name, files2] of dirGroups) {
    pillarGroups.push({ name, files: files2 });
  }
  const wildCandidates = highGravityFiles.filter((f) => f.cognitiveWeight >= 25);
  await writeGraph(projectRoot, graph);
  const uiUrl = `file://${join3(projectRoot, ".vibe-splainer", "ui", "index.html")}`;
  return {
    projectRoot,
    totalFilesScanned: files.length,
    highGravityFiles,
    pillarGroups,
    wildCandidates,
    uiUrl,
    graph
  };
}

// ../brain/dist/dossier.js
import { Mutex } from "async-mutex";
import { join as join4, dirname as dirname2 } from "path";
import { fileURLToPath as fileURLToPath2 } from "url";
import { readFile as readFile4, writeFile as writeFile3, mkdir as mkdir2 } from "fs/promises";
import { existsSync as existsSync3, cpSync } from "fs";
var __dirname2 = dirname2(fileURLToPath2(import.meta.url));
var dossierMutex = new Mutex();
async function readDossier(projectRoot) {
  const dossierPath = join4(projectRoot, ".vibe-splainer", "dossier.json");
  try {
    const raw = await readFile4(dossierPath, "utf8");
    return JSON.parse(raw);
  } catch {
    return null;
  }
}
async function writeDossier(projectRoot, dossier) {
  await dossierMutex.runExclusive(async () => {
    const dir = join4(projectRoot, ".vibe-splainer");
    await mkdir2(dir, { recursive: true });
    const dossierPath = join4(dir, "dossier.json");
    const tmp = dossierPath + ".tmp";
    await writeFile3(tmp, JSON.stringify(dossier, null, 2), "utf8");
    const { rename } = await import("fs/promises");
    await rename(tmp, dossierPath);
    await regenerateUI(projectRoot, dossier);
  });
}
async function regenerateUI(projectRoot, dossier) {
  const uiDir = join4(projectRoot, ".vibe-splainer", "ui");
  await mkdir2(uiDir, { recursive: true });
  let templateDir = join4(__dirname2, "ui");
  if (!existsSync3(templateDir)) {
    templateDir = join4(__dirname2, "../../cli/dist/ui");
  }
  if (!existsSync3(templateDir)) {
    console.error("[vibe-splain] UI template not found at", templateDir, "- skipping UI regeneration");
    return;
  }
  cpSync(templateDir, uiDir, { recursive: true });
  let html = await readFile4(join4(templateDir, "index.html"), "utf8");
  const injection = `<script>window.__VIBE_DOSSIER__ = ${JSON.stringify(dossier)};</script>`;
  html = html.replace("</head>", `${injection}
</head>`);
  await writeFile3(join4(uiDir, "index.html"), html, "utf8");
  console.error("[vibe-splain] UI regenerated at", join4(uiDir, "index.html"));
}
function validateMermaidNodeCount(diagram) {
  if (!diagram)
    return true;
  const nodePattern = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*[\[({|>]/gm;
  const statePattern = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:/gm;
  const nodes = /* @__PURE__ */ new Set();
  for (const match of diagram.matchAll(nodePattern))
    nodes.add(match[1]);
  for (const match of diagram.matchAll(statePattern))
    nodes.add(match[1]);
  if (diagram.includes("[*]"))
    nodes.add("[*]");
  return nodes.size <= 7;
}

// ../brain/dist/watcher.js
import chokidar from "chokidar";
import { createHash } from "crypto";
import { readFile as readFile5 } from "fs/promises";
function startWatcher(projectRoot, watchedPaths) {
  const watcher = chokidar.watch(watchedPaths.length > 0 ? watchedPaths : projectRoot, {
    ignoreInitial: true,
    ignored: ["**/node_modules/**", "**/dist/**", "**/build/**", "**/.vibe-splainer/**"],
    persistent: true
  });
  watcher.on("change", async (filepath) => {
    try {
      const dossier = await readDossier(projectRoot);
      if (!dossier)
        return;
      const content = await readFile5(filepath, "utf8");
      const newHash = createHash("sha256").update(content).digest("hex");
      let mutated = false;
      for (const pillar of dossier.pillars) {
        for (const card of pillar.decisions) {
          if (card.evidence.some((e) => e.file === filepath || filepath.endsWith(e.file))) {
            if (card.lastScannedHash !== newHash) {
              card.status = "stale";
              if (!dossier.stalePaths.includes(filepath))
                dossier.stalePaths.push(filepath);
              mutated = true;
            }
          }
        }
      }
      if (mutated)
        await writeDossier(projectRoot, dossier);
    } catch (err) {
      console.error("[vibe-splain] Watcher error:", err);
    }
  });
  console.error("[vibe-splain] File watcher started");
}

// dist/mcp/tools/scan_project.js
var scanProjectTool = {
  name: "scan_project",
  description: "Scans a codebase and returns its structural analysis. CALL THIS FIRST before any other tool. Returns High-Gravity files grouped by pillar, plus wildCandidates for unusual high-complexity files. After calling this tool, call get_file_context for each file in highGravityFiles, synthesize a narrative explaining WHY that code exists, then call write_decision_card to persist it. The uiUrl in the response is a file:// link \u2014 share it with the user so they can open the Dossier UI in their browser.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root directory to scan"
      }
    },
    required: ["projectRoot"]
  }
};
async function handleScanProject(args) {
  const projectRoot = args.projectRoot;
  if (!projectRoot)
    throw new Error("projectRoot is required");
  console.error(`[vibe-splain] Scanning project: ${projectRoot}`);
  const result = await scanProject(projectRoot);
  const existingDossier = await readDossier(projectRoot);
  const dossier = existingDossier || {
    version: "1.0.0",
    scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
    projectRoot,
    pillars: [],
    wildDiscoveries: [],
    stalePaths: []
  };
  dossier.scannedAt = (/* @__PURE__ */ new Date()).toISOString();
  for (const group of result.pillarGroups) {
    const existingPillar = dossier.pillars.find((p) => p.name === group.name);
    if (!existingPillar) {
      dossier.pillars.push({ name: group.name, cardCount: 0, decisions: [] });
    }
  }
  await writeDossier(projectRoot, dossier);
  const watchPaths = result.highGravityFiles.map((f) => f.path);
  startWatcher(projectRoot, watchPaths);
  console.error(`[vibe-splain] Scan complete. ${result.totalFilesScanned} files scanned, ${result.highGravityFiles.length} high-gravity files found.`);
  return {
    projectRoot: result.projectRoot,
    totalFilesScanned: result.totalFilesScanned,
    highGravityFiles: result.highGravityFiles.map((f) => ({
      relativePath: f.relativePath,
      cognitiveWeight: f.cognitiveWeight,
      pillars: f.pillars
    })),
    pillarGroups: result.pillarGroups.map((g) => ({
      name: g.name,
      fileCount: g.files.length,
      files: g.files.map((f) => f.relativePath)
    })),
    wildCandidates: result.wildCandidates.map((f) => ({
      relativePath: f.relativePath,
      cognitiveWeight: f.cognitiveWeight
    })),
    uiUrl: result.uiUrl
  };
}

// dist/mcp/tools/get_file_context.js
import { readFile as readFile6 } from "fs/promises";
import { join as join5, relative as relative2 } from "path";
var getFileContextTool = {
  name: "get_file_context",
  description: "Returns the full source code of a specific high-gravity file, its cognitive weight breakdown, and its import graph neighbors. Call this for each file you want to synthesize a Decision Card for. Use the source + neighbors to understand what the code does and WHY it was written that way.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root"
      },
      filePath: {
        type: "string",
        description: "Relative or absolute path to the file"
      }
    },
    required: ["projectRoot", "filePath"]
  }
};
async function handleGetFileContext(args) {
  const projectRoot = args.projectRoot;
  const filePath = args.filePath;
  if (!projectRoot || !filePath)
    throw new Error("projectRoot and filePath are required");
  const fullPath = filePath.startsWith("/") ? filePath : join5(projectRoot, filePath);
  const relPath = relative2(projectRoot, fullPath);
  const source = await readFile6(fullPath, "utf8");
  const graph = await readGraph(projectRoot);
  const neighbors = [];
  if (graph) {
    for (const edge of graph.edges) {
      if (edge.from === relPath)
        neighbors.push(edge.to);
      if (edge.to === relPath || edge.to.endsWith(relPath))
        neighbors.push(edge.from);
    }
  }
  return {
    filePath: relPath,
    source,
    lineCount: source.split("\n").length,
    neighbors: [...new Set(neighbors)]
  };
}

// dist/mcp/tools/write_decision_card.js
import { v4 as uuidv4 } from "uuid";
import { createHash as createHash2 } from "crypto";
import { readFile as readFile7 } from "fs/promises";
import { join as join6 } from "path";
var writeDecisionCardTool = {
  name: "write_decision_card",
  description: "Persists a Decision Card you have synthesized to the project's dossier. The narrative should be 3\u20135 sentences explaining WHY this code exists. Evidence must reference specific line ranges from the actual source. Diagrams are optional but use only stateDiagram-v2, flowchart TD, or linear A-->B-->C style, max 7 nodes. Will reject diagrams with more than 7 nodes.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root"
      },
      pillar: {
        type: "string",
        description: "The pillar this card belongs to (e.g., Auth, Database, etc.)"
      },
      title: {
        type: "string",
        description: "Short title for the decision card"
      },
      narrative: {
        type: "string",
        description: "3-5 sentences explaining WHY this code exists"
      },
      evidence: {
        type: "array",
        items: {
          type: "object",
          properties: {
            file: { type: "string", description: "Relative file path" },
            startLine: { type: "number", description: "Start line number" },
            endLine: { type: "number", description: "End line number" },
            snippet: { type: "string", description: "Code snippet from the file" }
          },
          required: ["file", "startLine", "endLine", "snippet"]
        },
        description: "Array of evidence items referencing specific code"
      },
      diagram: {
        type: "string",
        description: "Optional Mermaid diagram (stateDiagram-v2, flowchart TD, or linear style). Max 7 nodes."
      }
    },
    required: ["projectRoot", "pillar", "title", "narrative", "evidence"]
  }
};
async function handleWriteDecisionCard(args) {
  const projectRoot = args.projectRoot;
  const pillar = args.pillar;
  const title = args.title;
  const narrative = args.narrative;
  const evidence = args.evidence;
  const diagram = args.diagram || null;
  if (!projectRoot || !pillar || !title || !narrative || !evidence) {
    throw new Error("projectRoot, pillar, title, narrative, and evidence are required");
  }
  if (diagram && !validateMermaidNodeCount(diagram)) {
    throw new Error("Mermaid diagram exceeds maximum of 7 nodes. Simplify the diagram.");
  }
  let combinedContent = "";
  for (const e of evidence) {
    try {
      const fullPath = join6(projectRoot, e.file);
      const content = await readFile7(fullPath, "utf8");
      combinedContent += content;
    } catch {
      combinedContent += e.snippet;
    }
  }
  const hash = createHash2("sha256").update(combinedContent).digest("hex");
  const card = {
    id: uuidv4(),
    pillar,
    title,
    narrative,
    evidence,
    diagram,
    status: "fresh",
    lastScannedHash: hash
  };
  let dossier = await readDossier(projectRoot);
  if (!dossier) {
    dossier = {
      version: "1.0.0",
      scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
      projectRoot,
      pillars: [],
      wildDiscoveries: [],
      stalePaths: []
    };
  }
  let existingPillar = dossier.pillars.find((p) => p.name === pillar);
  if (!existingPillar) {
    existingPillar = { name: pillar, cardCount: 0, decisions: [] };
    dossier.pillars.push(existingPillar);
  }
  existingPillar.decisions.push(card);
  existingPillar.cardCount = existingPillar.decisions.length;
  await writeDossier(projectRoot, dossier);
  console.error(`[vibe-splain] Decision card written: "${title}" in pillar "${pillar}"`);
  return {
    success: true,
    cardId: card.id,
    pillar,
    title
  };
}

// dist/mcp/tools/get_strategic_overview.js
var getStrategicOverviewTool = {
  name: "get_strategic_overview",
  description: "Returns the current state of the dossier without evidence snippets (to save tokens). Use this to see what has already been analyzed and what is stale. Check stalePaths to know which files need re-analysis.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root"
      }
    },
    required: ["projectRoot"]
  }
};
async function handleGetStrategicOverview(args) {
  const projectRoot = args.projectRoot;
  if (!projectRoot)
    throw new Error("projectRoot is required");
  const dossier = await readDossier(projectRoot);
  if (!dossier) {
    return { error: "No dossier found. Run scan_project first." };
  }
  return {
    version: dossier.version,
    scannedAt: dossier.scannedAt,
    projectRoot: dossier.projectRoot,
    pillars: dossier.pillars.map((p) => ({
      name: p.name,
      cardCount: p.cardCount,
      decisions: p.decisions.map((d) => ({
        id: d.id,
        title: d.title,
        status: d.status,
        pillar: d.pillar,
        // Omit evidence snippets to save tokens
        evidenceFileCount: d.evidence.length,
        hasDiagram: !!d.diagram
      }))
    })),
    wildDiscoveriesCount: dossier.wildDiscoveries.length,
    stalePaths: dossier.stalePaths
  };
}

// dist/mcp/tools/inspect_pillar.js
var inspectPillarTool = {
  name: "inspect_pillar",
  description: "Returns all Decision Cards for a specific pillar including full evidence snippets. Use when you need deep detail on a specific area of the codebase.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root"
      },
      pillarName: {
        type: "string",
        description: "Name of the pillar to inspect"
      }
    },
    required: ["projectRoot", "pillarName"]
  }
};
async function handleInspectPillar(args) {
  const projectRoot = args.projectRoot;
  const pillarName = args.pillarName;
  if (!projectRoot || !pillarName)
    throw new Error("projectRoot and pillarName are required");
  const dossier = await readDossier(projectRoot);
  if (!dossier) {
    return { error: "No dossier found. Run scan_project first." };
  }
  const pillar = dossier.pillars.find((p) => p.name === pillarName);
  if (!pillar) {
    return {
      error: `Pillar "${pillarName}" not found. Available pillars: ${dossier.pillars.map((p) => p.name).join(", ")}`
    };
  }
  return pillar;
}

// dist/mcp/tools/get_wild_discoveries.js
var getWildDiscoveriesTool = {
  name: "get_wild_discoveries",
  description: "Returns files with extremely high cognitive complexity (weight \u2265 25) that don't fit standard patterns. These are the most surprising and important parts of the codebase to understand.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root"
      }
    },
    required: ["projectRoot"]
  }
};
async function handleGetWildDiscoveries(args) {
  const projectRoot = args.projectRoot;
  if (!projectRoot)
    throw new Error("projectRoot is required");
  const dossier = await readDossier(projectRoot);
  if (!dossier) {
    return { error: "No dossier found. Run scan_project first." };
  }
  return {
    wildDiscoveries: dossier.wildDiscoveries,
    count: dossier.wildDiscoveries.length
  };
}

// dist/mcp/tools/mark_stale.js
var markStaleTool = {
  name: "mark_stale",
  description: "Manually marks Decision Cards as stale when you detect a file has changed. The file watcher does this automatically, but call this if you modify a file yourself during a session.",
  inputSchema: {
    type: "object",
    properties: {
      projectRoot: {
        type: "string",
        description: "Absolute path to the project root"
      },
      filePaths: {
        type: "array",
        items: { type: "string" },
        description: "Array of relative file paths to mark as stale"
      }
    },
    required: ["projectRoot", "filePaths"]
  }
};
async function handleMarkStale(args) {
  const projectRoot = args.projectRoot;
  const filePaths = args.filePaths;
  if (!projectRoot || !filePaths)
    throw new Error("projectRoot and filePaths are required");
  const dossier = await readDossier(projectRoot);
  if (!dossier) {
    return { error: "No dossier found. Run scan_project first." };
  }
  let staleCount = 0;
  for (const filePath of filePaths) {
    for (const pillar of dossier.pillars) {
      for (const card of pillar.decisions) {
        if (card.evidence.some((e) => e.file === filePath || filePath.endsWith(e.file))) {
          card.status = "stale";
          staleCount++;
        }
      }
    }
    if (!dossier.stalePaths.includes(filePath)) {
      dossier.stalePaths.push(filePath);
    }
  }
  await writeDossier(projectRoot, dossier);
  return {
    success: true,
    staleCardsMarked: staleCount,
    totalStalePaths: dossier.stalePaths.length
  };
}

// dist/mcp/server.js
var ALL_TOOLS = [
  scanProjectTool,
  getFileContextTool,
  writeDecisionCardTool,
  getStrategicOverviewTool,
  inspectPillarTool,
  getWildDiscoveriesTool,
  markStaleTool
];
var TOOL_HANDLERS = {
  scan_project: handleScanProject,
  get_file_context: handleGetFileContext,
  write_decision_card: handleWriteDecisionCard,
  get_strategic_overview: handleGetStrategicOverview,
  inspect_pillar: handleInspectPillar,
  get_wild_discoveries: handleGetWildDiscoveries,
  mark_stale: handleMarkStale
};
async function startMCPServer() {
  await initParser();
  console.error("[vibe-splain] Tree-Sitter parser initialized");
  const server = new Server({ name: "vibe-splain", version: "1.0.0" }, { capabilities: { tools: {} } });
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools: ALL_TOOLS
  }));
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;
    const handler = TOOL_HANDLERS[name];
    if (!handler) {
      return {
        content: [{ type: "text", text: `Unknown tool: ${name}` }],
        isError: true
      };
    }
    try {
      const result = await handler(args || {});
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
      };
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      console.error(`[vibe-splain] Tool ${name} error:`, message);
      return {
        content: [{ type: "text", text: `Error: ${message}` }],
        isError: true
      };
    }
  });
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("[vibe-splain] MCP server running on stdio");
}

// dist/commands/serve.js
async function serveCommand() {
  console.error("[vibe-splain] Starting MCP server...");
  await startMCPServer();
}

// dist/index.js
var program = new Command();
program.name("vibe-splain").description("Architectural dossier engine for vibe-coded projects").version("1.0.0");
program.command("install").description("Patch coding agent MCP config files to register vibe-splain").action(installCommand);
program.command("serve").description("Start the MCP server (called by the coding agent, not by you)").action(serveCommand);
program.parse();
