{"version":3,"sources":["../../node_modules/tsup/assets/cjs_shims.js","../../src/cli/index.ts","../../src/cli/commands/init.ts","../../src/cli/commands/validate.ts","../../src/config/loader.ts","../../src/types/config.ts","../../src/config/defaults.ts","../../src/scanner/directory-scanner.ts","../../src/parsers/verbal-parser.ts","../../src/parsers/yaml-parser.ts","../../src/parsers/motion-parser.ts","../../src/parsers/markdown-parser.ts","../../src/parsers/css-parser.ts","../../src/parsers/font-parser.ts","../../src/context-resolver.ts","../../src/indexer/index.ts","../../src/cli/commands/docs.ts","../../src/cli/commands/preview.ts","../../src/indexer/hot-reload.ts","../../src/preview/server.ts","../../src/tools/search-brand.ts","../../src/index.ts","../../src/tools/index.ts","../../src/tools/get-brand-overview.ts","../../src/tools/_taste-primer.ts","../../src/tools/get-magic-trick.ts","../../src/tools/get-positioning.ts","../../src/tools/get-audience.ts","../../src/tools/get-messaging.ts","../../src/tools/get-differentiation.ts","../../src/tools/get-concepts.ts","../../src/tools/get-voice.ts","../../src/tools/get-colors-and-type.ts","../../src/tools/_context.ts","../../src/tools/get-assets.ts","../../src/tools/get-fonts.ts","../../src/tools/get-components.ts","../../src/tools/get-tokens.ts","../../src/formatters/token-formatters.ts","../../src/tools/get-motion.ts","../../src/tools/get-css.ts","../../src/tools/validate-usage.ts","../../src/tools/get-context-diff.ts","../../src/resources/index.ts","../../src/prompts/index.ts","../../src/version.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n  typeof document === \"undefined\" \n    ? new URL(`file:${__filename}`).href \n    : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n      ? document.currentScript.src \n      : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","#!/usr/bin/env node\n/**\n * @file cli/index.ts\n * @description BrandKit MCP CLI entry point.\n * Provides commands to initialize a new brand directory, validate the design\n * system, start the MCP server, launch the preview server, and generate\n * project documentation files.\n */\n\nimport { Command } from 'commander';\nimport { initCommand } from './commands/init.js';\nimport { validateCommand } from './commands/validate.js';\nimport { docsCommand } from './commands/docs.js';\nimport { previewCommand } from './commands/preview.js';\nimport { startServer } from '../index.js';\nimport { getPackageVersion } from '../version.js';\n\nconst program = new Command();\n\nprogram\n  .name('brandkit-mcp')\n  .description('Expose your company\\'s design system to AI tools via the Model Context Protocol')\n  .version(getPackageVersion());\n\nprogram\n  .command('init')\n  .description('Initialize a new brand directory with starter files and configuration')\n  .argument('[directory]', 'Target directory', '.')\n  .option('--name <name>', 'Brand name')\n  .option('--force', 'Overwrite existing files')\n  .action(initCommand);\n\nprogram\n  .command('validate')\n  .description('Validate the design system configuration and scan for issues')\n  .argument('[config-path]', 'Path to brandkit.config.yaml')\n  .action(validateCommand);\n\nprogram\n  .command('serve')\n  .description('Start the MCP server')\n  .option('--transport <type>', 'Transport type: stdio, sse, or http (Streamable HTTP)', 'stdio')\n  .option('--port <number>', 'Port for SSE transport', '3001')\n  .option('--config <path>', 'Path to brandkit.config.yaml')\n  .option('--watch', 'Enable hot reload on file changes')\n  .action(async (options) => {\n    await startServer({\n      transport: options.transport as 'stdio' | 'sse' | 'http',\n      port: parseInt(options.port, 10),\n      configPath: options.config,\n      watch: options.watch,\n    });\n  });\n\nprogram\n  .command('preview')\n  .description('Start the local preview UI for browsing the brand atomic system')\n  .option('--port <number>', 'Port for preview server', '3000')\n  .option('--config <path>', 'Path to brandkit.config.yaml')\n  .option('--watch', 'Enable hot reload on file changes')\n  .option('--open', 'Open browser automatically')\n  .action(async (options) => {\n    await previewCommand(options);\n  });\n\nprogram\n  .command('docs')\n  .description('Generate project documentation files (CLAUDE.md, AGENTS.md, SKILLS.md, DESIGN.md)')\n  .option('--config <path>', 'Path to brandkit.config.yaml')\n  .option('--output <dir>', 'Output directory for generated docs', '.')\n  .action(docsCommand);\n\n// If invoked with no subcommand and no flags, default to `serve` over stdio.\n// This is the behavior MCP clients (Claude Desktop, Glama mcp-proxy, etc.)\n// expect when they spawn `brandkit-mcp` as a child process: a stdio MCP\n// server that speaks JSON-RPC on stdin/stdout. Without this, running\n// `brandkit-mcp` bare prints help and exits, which clients interpret as a\n// connection-closed error.\nconst userArgs = process.argv.slice(2);\nconst knownCommands = new Set(['init', 'validate', 'serve', 'preview', 'docs', 'help']);\nconst isHelpOrVersion = userArgs.some((a) => ['-h', '--help', '-V', '--version'].includes(a));\nconst hasSubcommand = userArgs.length > 0 && knownCommands.has(userArgs[0]);\nif (!hasSubcommand && !isHelpOrVersion) {\n  // Inject `serve` so all flags the user passed (e.g. --config) still apply.\n  process.argv.splice(2, 0, 'serve');\n}\n\nprogram.parse();\n","import {\n  mkdirSync,\n  readdirSync,\n  copyFileSync,\n  statSync,\n  writeFileSync,\n  existsSync,\n  rmSync,\n} from 'fs';\nimport { isAbsolute, join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport yaml from 'js-yaml';\n\nfunction findTemplatesDir(): string {\n  const here = dirname(fileURLToPath(import.meta.url));\n  const candidates = [\n    join(here, '../../templates/starter/brand_atomic_system'),\n    join(here, '../../../templates/starter/brand_atomic_system'),\n    join(here, '../../../../templates/starter/brand_atomic_system'),\n  ];\n  for (const c of candidates) {\n    if (existsSync(c)) return c;\n  }\n  throw new Error(\n    `Could not locate bundled starter template (searched: ${candidates.join(', ')})`,\n  );\n}\n\nfunction copyRecursive(src: string, dst: string): void {\n  mkdirSync(dst, { recursive: true });\n  for (const entry of readdirSync(src)) {\n    const s = join(src, entry);\n    const d = join(dst, entry);\n    if (statSync(s).isDirectory()) {\n      copyRecursive(s, d);\n    } else {\n      copyFileSync(s, d);\n    }\n  }\n}\n\nexport async function initCommand(\n  directory: string,\n  options: { name?: string; force?: boolean },\n): Promise<void> {\n  const targetDir = isAbsolute(directory) ? directory : join(process.cwd(), directory);\n  const brandDir = join(targetDir, 'brand_atomic_system');\n\n  if (existsSync(brandDir) && !options.force) {\n    console.error('brand_atomic_system/ already exists. Use --force to overwrite.');\n    process.exit(1);\n  }\n\n  const brandName = options.name ?? 'Your Brand';\n\n  console.log(`Initializing BrandKit MCP v2 in ${targetDir}...`);\n\n  const templatesDir = findTemplatesDir();\n  mkdirSync(targetDir, { recursive: true });\n  // Remove any prior brand_atomic_system tree first so --force is a clean\n  // overwrite rather than a partial merge that can leave stale files behind.\n  rmSync(brandDir, { recursive: true, force: true });\n  copyRecursive(templatesDir, brandDir);\n\n  // The starter template ships only agent-readable content; create the\n  // human/ drop zone (PDFs, print specs) that the v2 layout documents.\n  mkdirSync(join(brandDir, 'human'), { recursive: true });\n  writeFileSync(\n    join(brandDir, 'human', 'readme.md'),\n    '# human/\\n\\nDrop PDFs, print specs, and other human-only material here.\\nThe MCP scanner ignores this directory entirely.\\n',\n  );\n\n  // Build the config as an object and serialize with js-yaml so brand names\n  // containing YAML metacharacters (e.g. `Acme: Corp`, `@handle`) are quoted\n  // correctly instead of producing an unparseable config.\n  writeFileSync(\n    join(targetDir, 'brandkit.config.yaml'),\n    yaml.dump({\n      version: 2,\n      brand: {\n        name: brandName,\n        description: 'Describe your brand here.',\n        root: './brand_atomic_system',\n      },\n      contexts: ['base', 'web', 'product'],\n      ignore: ['human/'],\n    }),\n  );\n\n  // A v1 install leaves a `brand/` directory that v2 ignores. Warn rather\n  // than silently leaving an orphaned tree alongside the new layout.\n  if (existsSync(join(targetDir, 'brand'))) {\n    console.warn(\n      'Note: a legacy v1 `brand/` directory is still present and is no longer used by v2. ' +\n        'Remove it once you have migrated its contents into brand_atomic_system/.',\n    );\n  }\n\n  console.log('');\n  console.log('BrandKit MCP initialized successfully!');\n  console.log('');\n  console.log('Next steps:');\n  console.log('  1. Edit brand_atomic_system/magic_trick.md with human-authored taste notes (AI never writes here).');\n  console.log('  2. Fill in brand_atomic_system/agent/verbal/{positioning,audience,messaging,differentiation,concepts,voice}.');\n  console.log('  3. Add tokens to brand_atomic_system/agent/visual/colors_and_type.css and tokens/.');\n  console.log('  4. Drop logos and fonts into brand_atomic_system/agent/visual/{assets,fonts}/.');\n  console.log('  5. Run `brandkit-mcp serve` to start the MCP server.');\n  console.log('  6. Connect to Claude Desktop (see README.md).');\n}\n","/**\n * @file commands/validate.ts\n * @description Implementation of the `brandkit-mcp validate` command.\n * Validates the configuration and scans the brand directory for issues.\n */\n\nimport { existsSync } from 'fs';\nimport { dirname } from 'path';\nimport { loadConfigWithPath, resolveConfigPaths } from '../../config/loader.js';\nimport type { BrandKitConfig } from '../../types/config.js';\nimport { buildDesignSystemIndex } from '../../indexer/index.js';\n\n/**\n * Handles the `brandkit-mcp validate [config-path]` command.\n * @param configPath - Optional path to brandkit.config.yaml\n */\nexport async function validateCommand(configPath?: string): Promise<void> {\n  console.log('Validating BrandKit MCP configuration...\\n');\n\n  let config: BrandKitConfig;\n  try {\n    const { config: rawConfig, filePath } = loadConfigWithPath(configPath);\n    config = resolveConfigPaths(rawConfig, dirname(filePath));\n    console.log('[OK] Configuration loaded successfully');\n    console.log(`     Brand name: ${config.brand.name}`);\n  } catch (err) {\n    console.error('[ERROR] Failed to load configuration:', err instanceof Error ? err.message : err);\n    process.exit(1);\n  }\n\n  // Check directory structure\n  const dirs = [\n    { path: config.brand.root, label: 'Brand root directory' },\n  ];\n\n  let hasErrors = false;\n  for (const dir of dirs) {\n    if (existsSync(dir.path)) {\n      console.log(`[OK] ${dir.label} found: ${dir.path}`);\n    } else {\n      console.log(`[WARN] ${dir.label} not found: ${dir.path}`);\n    }\n  }\n\n  // Build index and report\n  try {\n    console.log('\\nScanning design system files...\\n');\n    const index = await buildDesignSystemIndex(config);\n\n    console.log('Asset Inventory (base context):');\n    console.log(`  Tokens:      ${index.base.tokens.length}`);\n    console.log(`  Components:  ${index.base.components.length}`);\n    console.log(`  Fonts:       ${index.base.fonts.length}`);\n    console.log(`  Assets:      ${index.base.assets.length}`);\n    console.log(`  Motion:      ${index.base.motion != null ? 'yes' : 'no'}`);\n\n    console.log('\\nVerbal Layer:');\n    console.log(`  Positioning: ${index.verbal.positioning != null ? 'yes' : 'no'}`);\n    console.log(`  Audience:    ${index.verbal.audience != null ? 'yes' : 'no'}`);\n    console.log(`  Messaging:   ${index.verbal.messaging != null ? 'yes' : 'no'}`);\n    console.log(`  Differentiation: ${index.verbal.differentiation != null ? 'yes' : 'no'}`);\n    console.log(`  Concepts:    ${index.verbal.concepts != null ? 'yes' : 'no'}`);\n    console.log(`  Voice:       ${index.verbal.voice != null ? 'yes' : 'no'}`);\n    console.log(`  Magic Trick: ${index.magicTrick != null ? 'yes' : 'no'}`);\n\n    if (index.warnings.length > 0) {\n      console.log('\\nWarnings:');\n      for (const w of index.warnings) {\n        console.log(`  [WARN] ${w}`);\n      }\n    }\n\n    const totalAssets = index.base.tokens.length + index.base.components.length + index.base.assets.length;\n    if (totalAssets === 0) {\n      console.log('\\n[WARN] No design system files found. Add files to the brand root directory.');\n      hasErrors = true;\n    } else {\n      console.log('\\n[OK] Validation passed.');\n    }\n  } catch (err) {\n    console.error('\\n[ERROR] Failed to build design system index:', err instanceof Error ? err.message : err);\n    hasErrors = true;\n  }\n\n  process.exit(hasErrors ? 1 : 0);\n}\n","/**\n * @file loader.ts\n * @description Config loader for brandkit.config.yaml.\n *\n * Responsible for:\n *   1. Locating the config file (explicit path or auto-discovery)\n *   2. Parsing the YAML content\n *   3. Validating against the Zod schema\n *   4. Resolving relative directory paths to absolute paths\n */\n\nimport { readFileSync, existsSync } from 'fs';\nimport { dirname, join, resolve } from 'path';\nimport { fileURLToPath } from 'url';\nimport yaml from 'js-yaml';\nimport { BrandKitConfigSchema, BrandkitV1ConfigError, type BrandKitConfig } from '../types/config.js';\nimport { DEFAULT_CONFIG_FILENAMES } from './defaults.js';\n\n/**\n * Returns the directories that should be searched (in order) when no\n * explicit config path is provided. Searching multiple locations lets\n * brandkit-mcp work in environments where the spawning process (Claude\n * Desktop, mcp-proxy, npx, etc.) sets a working directory that differs\n * from where the brand assets live.\n *\n * Order:\n *   1. $BRANDKIT_CONFIG (explicit override directory or file)\n *   2. process.cwd()\n *   3. Walk up from the running script's directory looking for a config\n *      (covers the Docker case where WORKDIR contains brandkit.config.yaml\n *      but the runtime cwd is something else like / or /tmp).\n */\nfunction candidateConfigPaths(): string[] {\n  const candidates: string[] = [];\n\n  const envOverride = process.env.BRANDKIT_CONFIG;\n  if (envOverride) {\n    candidates.push(resolve(envOverride));\n  }\n\n  const cwd = process.cwd();\n  for (const name of DEFAULT_CONFIG_FILENAMES) {\n    candidates.push(join(cwd, name));\n  }\n\n  // Walk up from the running script (e.g. /app/dist/cli/index.js) up to\n  // a few levels. At each level, probe both the directory itself and a\n  // small set of well-known bundled-demo subdirectories. This lets the\n  // server start out-of-the-box when:\n  //   - run from the source repo (Glama auto-build, npm-published package):\n  //     templates/starter/ and examples/acme-corp/ ship a working brand\n  //   - run from our Docker image: brandkit.config.yaml lives at /app\n  //   - run via `npx brandkit-mcp` with no local config: falls back to\n  //     the bundled starter template\n  const BUNDLED_SUBDIRS = ['', 'templates/starter', 'examples/acme-corp'];\n  try {\n    const scriptDir = dirname(fileURLToPath(import.meta.url));\n    let dir = scriptDir;\n    for (let i = 0; i < 6; i++) {\n      for (const sub of BUNDLED_SUBDIRS) {\n        const base = sub ? join(dir, sub) : dir;\n        for (const name of DEFAULT_CONFIG_FILENAMES) {\n          candidates.push(join(base, name));\n        }\n      }\n      const parent = dirname(dir);\n      if (parent === dir) break;\n      dir = parent;\n    }\n  } catch {\n    // import.meta.url may be unavailable in unusual runtimes; ignore.\n  }\n\n  return candidates;\n}\n\n/**\n * Detects if a parsed YAML object contains v1 config markers.\n *\n * V1 configs have:\n *   - A top-level `name` field (not nested under `brand`)\n *   - A top-level `paths` field (v2 nests paths differently)\n *   - A `contexts` field with `marketing` or `product` as objects (v2 has `contexts` as an array)\n *\n * @param parsed - The parsed YAML object\n * @returns true if v1 markers are detected\n */\nfunction isV1Config(parsed: Record<string, unknown>): boolean {\n  // V1 had top-level `name` field\n  if (typeof parsed.name === 'string') {\n    return true;\n  }\n\n  // V1 had top-level `paths` field\n  if (parsed.paths && typeof parsed.paths === 'object') {\n    return true;\n  }\n\n  // V1 had `contexts` as an object with `marketing`/`product` keys\n  if (\n    parsed.contexts &&\n    typeof parsed.contexts === 'object' &&\n    !Array.isArray(parsed.contexts) &&\n    ('marketing' in parsed.contexts || 'product' in parsed.contexts)\n  ) {\n    return true;\n  }\n\n  return false;\n}\n\n/**\n * Parses YAML text and validates it as a v2 BrandKit config.\n *\n * Detects v1 configs and throws BrandkitV1ConfigError with migration guidance.\n * Otherwise validates against the v2 schema and returns the parsed config.\n *\n * @param yamlText - The YAML content to parse\n * @param sourcePath - The source file path (for error messages)\n * @returns A validated BrandKitConfig\n * @throws {BrandkitV1ConfigError} If a v1 config is detected\n * @throws {Error} If the config is invalid or parsing fails\n */\nexport function loadConfigFromString(yamlText: string, sourcePath: string): BrandKitConfig {\n  let parsed: unknown;\n  try {\n    parsed = yaml.load(yamlText);\n  } catch (err) {\n    throw new Error(`Failed to parse YAML at ${sourcePath}: ${err instanceof Error ? err.message : String(err)}`);\n  }\n\n  if (!parsed || typeof parsed !== 'object') {\n    throw new Error(`Config at ${sourcePath} must be an object`);\n  }\n\n  const parsedObj = parsed as Record<string, unknown>;\n\n  // Detect v1 config markers\n  if (isV1Config(parsedObj)) {\n    throw new BrandkitV1ConfigError(\n      `v1 config detected at ${sourcePath}. ` +\n        'Migrate to v2: see docs/superpowers/specs/2026-05-14-brand-atomic-system-restructure-design.md',\n    );\n  }\n\n  // CLAUDE.md contract: a config without `version: 2` throws\n  // BrandkitV1ConfigError with migration guidance, even when no positive\n  // v1 marker is present.\n  if (parsedObj.version !== 2) {\n    throw new BrandkitV1ConfigError(\n      `Config at ${sourcePath} is missing \\`version: 2\\` (found: ${JSON.stringify(parsedObj.version)}). ` +\n        'BrandKit v2 requires `version: 2`. ' +\n        'Migrate to v2: see docs/superpowers/specs/2026-05-14-brand-atomic-system-restructure-design.md',\n    );\n  }\n\n  // Validate against v2 schema\n  const result = BrandKitConfigSchema.safeParse(parsedObj);\n\n  if (!result.success) {\n    const issues = result.error.issues.map((i) => `  - ${i.path.join('.')}: ${i.message}`).join('\\n');\n    throw new Error(`Invalid config in ${sourcePath}:\\n${issues}`);\n  }\n\n  return result.data;\n}\n\n/**\n * Like {@link loadConfig} but also returns the absolute path of the\n * config file that was loaded. Useful for callers that need to resolve\n * relative paths in the config against the config's directory rather\n * than the current working directory.\n */\nexport function loadConfigWithPath(configPath?: string): { config: BrandKitConfig; filePath: string } {\n  const filePath = resolveConfigFilePath(configPath);\n  const raw = readFileSync(filePath, 'utf-8');\n  const config = loadConfigFromString(raw, filePath);\n\n  return { config, filePath };\n}\n\nfunction resolveConfigFilePath(configPath?: string): string {\n  if (configPath) {\n    const filePath = resolve(configPath);\n    if (!existsSync(filePath)) {\n      throw new Error(`Config file not found: ${filePath}`);\n    }\n    return filePath;\n  }\n\n  for (const candidate of candidateConfigPaths()) {\n    if (existsSync(candidate)) return candidate;\n  }\n\n  throw new Error(\n    `No config file found. Searched for ${DEFAULT_CONFIG_FILENAMES.join(', ')} ` +\n    `in $BRANDKIT_CONFIG, ${process.cwd()}, and the install directory.\\n` +\n    'Run `brandkit-mcp init` to create one, or set BRANDKIT_CONFIG to point at one.',\n  );\n}\n\n/**\n * Finds and loads brandkit.config.yaml from the given path or by\n * searching the current working directory for known config filenames.\n *\n * @param configPath - Optional explicit path to a config file.\n * @returns A validated (but not path-resolved) BrandKitConfig.\n * @throws {Error} If no config file is found or validation fails.\n */\nexport function loadConfig(configPath?: string): BrandKitConfig {\n  return loadConfigWithPath(configPath).config;\n}\n\n/**\n * Resolves relative directory paths in the config to absolute paths.\n *\n * @param config - A validated BrandKitConfig with potentially relative paths.\n * @param basePath - The directory to resolve relative paths against (usually cwd).\n * @returns A new config object with absolute paths.\n */\nexport function resolveConfigPaths(config: BrandKitConfig, basePath: string): BrandKitConfig {\n  return {\n    ...config,\n    brand: {\n      ...config.brand,\n      root: resolve(basePath, config.brand.root),\n    },\n  };\n}\n","import { z } from 'zod';\n\nexport class BrandkitV1ConfigError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = 'BrandkitV1ConfigError';\n  }\n}\n\nexport const BrandKitConfigSchema = z.object({\n  version: z.literal(2, {\n    errorMap: () => ({\n      message:\n        'BrandKit v2 requires `version: 2`. See docs/superpowers/specs/2026-05-14-brand-atomic-system-restructure-design.md for migration.',\n    }),\n  }),\n  brand: z.object({\n    name: z.string().min(1, 'brand.name is required'),\n    description: z.string().optional(),\n    root: z.string().default('./brand_atomic_system'),\n  }),\n  // RESERVED: accepted for forward compatibility but not yet honored — the\n  // resolver always materializes all three contexts. See CLAUDE.md.\n  contexts: z\n    .array(z.enum(['base', 'web', 'product']))\n    .default(['base', 'web', 'product']),\n  ignore: z.array(z.string()).default(['human/']),\n  preview: z\n    .object({\n      port: z.number().int().min(1).max(65535).default(3000),\n      host: z.string().default('localhost'),\n    })\n    .default({}),\n  server: z\n    .object({\n      transport: z.enum(['stdio', 'sse']).default('stdio'),\n      port: z.number().int().min(1).max(65535).default(3001),\n      host: z.string().default('localhost'),\n    })\n    .default({}),\n});\n\nexport type BrandKitConfig = z.infer<typeof BrandKitConfigSchema>;\n","/**\n * @file defaults.ts\n * @description Default values and constants for BrandKit MCP configuration.\n *\n * This module serves two purposes:\n *   1. Provides the canonical list of config filenames the loader searches for.\n *   2. Exports a fully populated default config object that other modules\n *      can reference when they need fallback values.\n *\n * Note: Zod's `.default()` calls in the schema handle most defaulting at\n * parse time. The DEFAULT_CONFIG here is useful for documentation, tests,\n * and any code path that needs a config before YAML is loaded.\n */\n\nimport { BrandKitConfigSchema, type BrandKitConfig } from '../types/config.js';\n\n/**\n * Ordered list of filenames the config loader searches for when no\n * explicit path is provided.\n *\n * The loader stops at the first match, so order expresses preference:\n *   1. `brandkit.config.yaml`  -- recommended canonical name\n *   2. `brandkit.config.yml`   -- common YAML extension variant\n *   3. `.brandkitrc.yaml`      -- rc-file convention\n *   4. `.brandkitrc.yml`       -- rc-file with .yml extension\n */\nexport const DEFAULT_CONFIG_FILENAMES: readonly string[] = [\n  'brandkit.config.yaml',\n  'brandkit.config.yml',\n  '.brandkitrc.yaml',\n  '.brandkitrc.yml',\n] as const;\n\n/**\n * A complete BrandKitConfig populated entirely with default values.\n *\n * Useful for:\n *   - Unit tests that need a baseline config without touching the filesystem\n *   - Fallback values when optional config sections are missing\n *   - Documentation of the \"zero-config\" baseline\n *\n * The `brand.root` here is relative. In production it is resolved\n * to an absolute path by {@link resolveConfigPaths} in `loader.ts`.\n */\nexport const DEFAULT_CONFIG: BrandKitConfig = BrandKitConfigSchema.parse({\n  version: 2,\n  brand: { name: 'BrandKit' },\n});\n\n/**\n * Returns a deep copy of the default config, safe for mutation.\n *\n * Prefer this over directly referencing `DEFAULT_CONFIG` when you\n * intend to modify values (e.g. in test setup).\n *\n * @returns A fresh deep copy of the default BrandKit configuration.\n */\nexport function getDefaultConfig(): BrandKitConfig {\n  return structuredClone(DEFAULT_CONFIG);\n}\n\n/**\n * Standard directory names within a brand folder.\n *\n * Parsers use these to auto-discover assets by convention:\n *   brand_atomic_system/\n *     base/             -- base context (shared assets)\n *       colors/\n *       typography/\n *       logos/\n *       textures/\n *       components/\n *       guidelines/\n *       fonts/\n *       css/\n *     web/              -- web context overrides\n *       colors/\n *       ...\n *     product/          -- product context overrides\n *       colors/\n *       ...\n */\nexport const ASSET_DIRECTORY_NAMES = {\n  /** Color palette definitions (CSS, YAML, or Markdown) */\n  colors: 'colors',\n  /** Typography scale definitions */\n  typography: 'typography',\n  /** Logo files and usage guidelines */\n  logos: 'logos',\n  /** Background textures and patterns */\n  textures: 'textures',\n  /** UI component documentation */\n  components: 'components',\n  /** Prose guidelines (brand voice, accessibility, etc.) */\n  guidelines: 'guidelines',\n  /** Web font files (.woff2, .otf, .ttf, .woff) */\n  fonts: 'fonts',\n  /** CSS stylesheets with custom properties */\n  css: 'css',\n  /** PDF brand documents */\n  pdfs: 'pdfs',\n} as const;\n\n/** File extensions recognized by each parser category */\nexport const RECOGNIZED_EXTENSIONS = {\n  /** Extensions the color parser can handle */\n  colors: ['.css', '.yaml', '.yml', '.md', '.json'] as const,\n  /** Extensions the typography parser can handle */\n  typography: ['.css', '.yaml', '.yml', '.md', '.json'] as const,\n  /** Extensions the logo parser can handle */\n  logos: ['.svg', '.png', '.jpg', '.jpeg', '.webp'] as const,\n  /** Extensions the texture parser can handle */\n  textures: ['.svg', '.png', '.jpg', '.jpeg', '.webp'] as const,\n  /** Extensions the font parser can handle */\n  fonts: ['.woff2', '.otf', '.ttf', '.woff'] as const,\n  /** Extensions the CSS parser can handle */\n  css: ['.css'] as const,\n  /** Extensions the guideline parser can handle */\n  guidelines: ['.md', '.txt'] as const,\n  /** Extensions the PDF parser can handle */\n  pdfs: ['.pdf'] as const,\n  /** Extensions the component parser can handle */\n  components: ['.md', '.yaml', '.yml', '.json'] as const,\n} as const;\n","/**\n * @file directory-scanner.ts\n * @description Walks the v2 brand_atomic_system directory layout and produces\n * a fully-parsed ScanResult ready for the indexer to resolve and merge.\n *\n * v2 layout expected:\n *   <root>/magic_trick.md\n *   <root>/agent/verbal/{positioning,messaging,differentiation,concepts,voice}.md\n *   <root>/agent/verbal/audience.yaml\n *   <root>/agent/visual/colors_and_type.css\n *   <root>/agent/visual/components/*.md\n *   <root>/agent/visual/tokens/*.md\n *   <root>/agent/visual/motion/\n *   <root>/agent/visual/fonts/  (+ optional fonts.yaml)\n *   <root>/agent/visual/assets/ (+ optional assets.yaml)\n *   <root>/agent/visual/artifacts/web/   (same sub-structure, all optional)\n *   <root>/agent/visual/artifacts/product/ (same)\n */\n\nimport { readdirSync, statSync, existsSync, readFileSync, realpathSync } from 'fs';\nimport { join, extname, relative, sep, basename } from 'path';\nimport type {\n  MagicTrick,\n  AudienceDoc,\n  MotionSystem,\n  AssetEntry,\n  FontFace,\n} from '../types/design-system.js';\nimport type { RawContextData, VerbalLayer } from '../indexer/types.js';\nimport { parseVerbalDoc } from '../parsers/verbal-parser.js';\nimport { parseYamlFile } from '../parsers/yaml-parser.js';\nimport { parseMotionDir } from '../parsers/motion-parser.js';\nimport { parseTokenSpecimen } from '../parsers/markdown-parser.js';\nimport { parseComponentMarkdown } from '../parsers/markdown-parser.js';\nimport { parseCSSFile } from '../parsers/css-parser.js';\nimport { parseFontFile } from '../parsers/font-parser.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface ScanResult {\n  magicTrick: MagicTrick | undefined;\n  verbal: VerbalLayer;\n  base: RawContextData;\n  web: RawContextData;\n  product: RawContextData;\n  warnings: string[];\n}\n\nexport interface ScanOptions {\n  /** Directory prefix patterns to skip (relative to rootDir). Defaults to ['human/']. */\n  ignore?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Main export\n// ---------------------------------------------------------------------------\n\n/**\n * Scan a v2 brand_atomic_system directory and return fully-parsed raw data.\n * Never throws on user content — bad input becomes a warning.\n *\n * @param rootDir - Absolute path to the brand root directory\n * @param options - Optional scan configuration\n */\nexport function scanBrandRoot(rootDir: string, options?: ScanOptions): ScanResult {\n  const ignore = options?.ignore ?? ['human/'];\n  const warnings: string[] = [];\n\n  // ---------------------------------------------------------------------------\n  // 1. magic_trick.md\n  // ---------------------------------------------------------------------------\n  const magicTrick = parseMagicTrick(rootDir, warnings);\n\n  // ---------------------------------------------------------------------------\n  // 2. Verbal layer\n  // ---------------------------------------------------------------------------\n  const verbal = parseVerbalLayer(rootDir, warnings);\n\n  // ---------------------------------------------------------------------------\n  // 3. Base visual layer (agent/visual/)\n  // ---------------------------------------------------------------------------\n  const baseVisualDir = join(rootDir, 'agent', 'visual');\n  const base = parseVisualDir(baseVisualDir, 'base', ignore, warnings);\n\n  // ---------------------------------------------------------------------------\n  // 4. Web overrides (agent/visual/artifacts/web/)\n  // ---------------------------------------------------------------------------\n  const webVisualDir = join(rootDir, 'agent', 'visual', 'artifacts', 'web');\n  const web = parseVisualDir(webVisualDir, 'web', ignore, warnings);\n\n  // ---------------------------------------------------------------------------\n  // 5. Product overrides (agent/visual/artifacts/product/)\n  // ---------------------------------------------------------------------------\n  const productVisualDir = join(rootDir, 'agent', 'visual', 'artifacts', 'product');\n  const product = parseVisualDir(productVisualDir, 'product', ignore, warnings);\n\n  return { magicTrick, verbal, base, web, product, warnings };\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction parseMagicTrick(rootDir: string, warnings: string[]): MagicTrick | undefined {\n  const filePath = join(rootDir, 'magic_trick.md');\n  if (!existsSync(filePath)) return undefined;\n  try {\n    const content = readFileSync(filePath, 'utf-8');\n    return { content: content.trim(), source: filePath };\n  } catch (err) {\n    warnings.push(`Could not read magic_trick.md: ${(err as Error).message}`);\n    return undefined;\n  }\n}\n\nfunction parseVerbalLayer(rootDir: string, warnings: string[]): VerbalLayer {\n  const verbalDir = join(rootDir, 'agent', 'verbal');\n\n  // positioning\n  const positioning = parseVerbalDoc(join(verbalDir, 'positioning.md'));\n\n  // messaging\n  const messaging = parseVerbalDoc(join(verbalDir, 'messaging.md'));\n\n  // differentiation\n  const differentiation = parseVerbalDoc(join(verbalDir, 'differentiation.md'));\n\n  // concepts\n  const concepts = parseVerbalDoc(join(verbalDir, 'concepts.md'));\n\n  // voice\n  const voice = parseVerbalDoc(join(verbalDir, 'voice.md'));\n\n  // audience (YAML)\n  let audience: AudienceDoc | undefined;\n  const audiencePath = join(verbalDir, 'audience.yaml');\n  if (existsSync(audiencePath)) {\n    const result = parseYamlFile(audiencePath);\n    warnings.push(...result.warnings);\n    if (result.data !== null) {\n      audience = { data: result.data, source: result.source };\n    }\n  }\n\n  return { positioning, messaging, differentiation, concepts, voice, audience };\n}\n\nfunction emptyRawContextData(): RawContextData {\n  return {\n    colorsAndType: undefined,\n    components: [],\n    tokens: [],\n    assets: [],\n    fonts: [],\n    motion: undefined,\n  };\n}\n\nfunction parseVisualDir(\n  visualDir: string,\n  _contextLabel: string,\n  ignore: string[],\n  warnings: string[],\n): RawContextData {\n  if (!existsSync(visualDir)) return emptyRawContextData();\n\n  const data = emptyRawContextData();\n\n  // colors_and_type.css\n  const cssPath = join(visualDir, 'colors_and_type.css');\n  if (existsSync(cssPath)) {\n    try {\n      data.colorsAndType = parseCSSFile(cssPath, 'base');\n    } catch (err) {\n      warnings.push(`Failed to parse ${cssPath}: ${(err as Error).message}`);\n    }\n  }\n\n  // components/*.md\n  const componentsDir = join(visualDir, 'components');\n  if (existsSync(componentsDir) && isDirectory(componentsDir)) {\n    for (const file of listFiles(componentsDir, ['.md'], ignore, visualDir)) {\n      try {\n        const parsed = parseComponentMarkdown(file, 'base');\n        data.components.push(...parsed);\n      } catch (err) {\n        warnings.push(`Failed to parse component ${file}: ${(err as Error).message}`);\n      }\n    }\n  }\n\n  // tokens/*.md\n  const tokensDir = join(visualDir, 'tokens');\n  if (existsSync(tokensDir) && isDirectory(tokensDir)) {\n    for (const file of listFiles(tokensDir, ['.md'], ignore, visualDir)) {\n      try {\n        const { specimen, warnings: w } = parseTokenSpecimen(file);\n        warnings.push(...w);\n        if (specimen !== null) {\n          data.tokens.push(specimen);\n        }\n      } catch (err) {\n        warnings.push(`Failed to parse token ${file}: ${(err as Error).message}`);\n      }\n    }\n  }\n\n  // motion/\n  const motionDir = join(visualDir, 'motion');\n  if (existsSync(motionDir) && isDirectory(motionDir)) {\n    try {\n      const result = parseMotionDir(motionDir);\n      // A CSS-only motion system is valid: suppress the \"No motion.json\"\n      // warning when motion.css is present.\n      const filtered = result.css\n        ? result.warnings.filter((w) => !w.startsWith('No motion.json found'))\n        : result.warnings;\n      warnings.push(...filtered);\n      if (result.tokens !== null || result.css) {\n        const motion: MotionSystem = {\n          tokens: result.tokens,\n          css: result.css,\n          source: result.source,\n        };\n        data.motion = motion;\n      }\n    } catch (err) {\n      warnings.push(`Failed to parse motion dir ${motionDir}: ${(err as Error).message}`);\n    }\n  }\n\n  // fonts/\n  const fontsDir = join(visualDir, 'fonts');\n  if (existsSync(fontsDir) && isDirectory(fontsDir)) {\n    data.fonts = parseFontsDir(fontsDir, ignore, visualDir, warnings);\n  }\n\n  // assets/\n  const assetsDir = join(visualDir, 'assets');\n  if (existsSync(assetsDir) && isDirectory(assetsDir)) {\n    data.assets = parseAssetsDir(assetsDir, ignore, visualDir, warnings);\n  }\n\n  return data;\n}\n\n// Font extensions\nconst FONT_EXTENSIONS = new Set(['.woff2', '.woff', '.otf', '.ttf']);\n\n// Image extensions\nconst IMAGE_EXTENSIONS = new Set(['.svg', '.png', '.jpg', '.jpeg', '.gif', '.webp']);\n\nfunction parseFontsDir(\n  fontsDir: string,\n  ignore: string[],\n  visualRoot: string,\n  warnings: string[],\n): FontFace[] {\n  const fonts: FontFace[] = [];\n\n  // Load optional fonts.yaml for metadata overrides\n  const fontsYamlPath = join(fontsDir, 'fonts.yaml');\n  let fontsYamlData: Record<string, unknown> | null = null;\n  if (existsSync(fontsYamlPath)) {\n    const result = parseYamlFile(fontsYamlPath);\n    warnings.push(...result.warnings);\n    if (result.data && typeof result.data === 'object') {\n      fontsYamlData = result.data as Record<string, unknown>;\n    }\n  }\n\n  // Build a lookup from file name -> metadata from YAML\n  // Expected YAML shape: { faces: [{ family, weight, style, file }] }\n  const yamlFaceMap = new Map<string, { family?: string; weight?: string | number; style?: string }>();\n  if (fontsYamlData?.faces && Array.isArray(fontsYamlData.faces)) {\n    for (const face of fontsYamlData.faces as Array<Record<string, unknown>>) {\n      if (typeof face.file === 'string') {\n        yamlFaceMap.set(face.file, {\n          family: face.family as string | undefined,\n          weight: face.weight as string | number | undefined,\n          style: face.style as string | undefined,\n        });\n      }\n    }\n  }\n\n  // If we have YAML faces but no physical font files (metadata-only approach),\n  // create FontFace entries from the YAML directly\n  const physicalFontFiles = listFiles(fontsDir, [...FONT_EXTENSIONS], ignore, visualRoot);\n\n  if (physicalFontFiles.length > 0) {\n    // Parse physical font files, merging YAML metadata\n    for (const filePath of physicalFontFiles) {\n      try {\n        const parsed = parseFontFile(filePath);\n        const fileName = basename(filePath);\n        const yamlMeta = yamlFaceMap.get(fileName);\n\n        const ext = extname(filePath).toLowerCase().replace('.', '') as FontFace['format'];\n        const fontFace: FontFace = {\n          family: yamlMeta?.family ?? parsed.family,\n          weight: yamlMeta?.weight ?? parsed.weight,\n          style: (yamlMeta?.style as 'normal' | 'italic' | undefined) ?? parsed.style ?? 'normal',\n          file: fileName,\n          filePath,\n          format: ext,\n        };\n        fonts.push(fontFace);\n      } catch (err) {\n        warnings.push(`Failed to parse font file ${filePath}: ${(err as Error).message}`);\n      }\n    }\n  } else if (yamlFaceMap.size > 0) {\n    // No physical files — create entries from YAML metadata only\n    for (const [file, meta] of yamlFaceMap) {\n      const rawExt = extname(file).toLowerCase().replace('.', '');\n      if (!FONT_EXTENSIONS.has('.' + rawExt)) {\n        // not a font extension, skip\n        continue;\n      }\n      const ext = rawExt as FontFace['format'];\n      fonts.push({\n        family: meta.family ?? 'Unknown',\n        weight: meta.weight,\n        style: (meta.style as 'normal' | 'italic' | undefined) ?? 'normal',\n        file,\n        filePath: join(fontsDir, file),\n        format: ext || 'woff2',\n      });\n    }\n  }\n\n  return fonts;\n}\n\nfunction parseAssetsDir(\n  assetsDir: string,\n  ignore: string[],\n  visualRoot: string,\n  warnings: string[],\n): AssetEntry[] {\n  const assets: AssetEntry[] = [];\n\n  // Load optional assets.yaml for metadata\n  const assetsYamlPath = join(assetsDir, 'assets.yaml');\n  let assetsYamlData: Record<string, unknown> | null = null;\n  if (existsSync(assetsYamlPath)) {\n    const result = parseYamlFile(assetsYamlPath);\n    warnings.push(...result.warnings);\n    if (result.data && typeof result.data === 'object') {\n      assetsYamlData = result.data as Record<string, unknown>;\n    }\n  }\n\n  // Build a lookup from file name -> YAML metadata\n  // Expected shape: { assets: [{ id, file, purpose }] }\n  const yamlAssetMap = new Map<string, { id?: string; purpose?: string }>();\n  if (assetsYamlData?.assets && Array.isArray(assetsYamlData.assets)) {\n    for (const asset of assetsYamlData.assets as Array<Record<string, unknown>>) {\n      if (typeof asset.file === 'string') {\n        yamlAssetMap.set(asset.file, {\n          id: asset.id as string | undefined,\n          purpose: asset.purpose as string | undefined,\n        });\n      }\n    }\n  }\n\n  const physicalAssetFiles = listFiles(assetsDir, [...IMAGE_EXTENSIONS], ignore, visualRoot);\n\n  if (physicalAssetFiles.length > 0) {\n    for (const filePath of physicalAssetFiles) {\n      const fileName = basename(filePath);\n      const ext = extname(filePath).toLowerCase().replace('.', '');\n      const yamlMeta = yamlAssetMap.get(fileName);\n      assets.push({\n        id: yamlMeta?.id,\n        file: fileName,\n        purpose: yamlMeta?.purpose,\n        format: ext,\n        filePath,\n      });\n    }\n  } else if (yamlAssetMap.size > 0) {\n    // No physical files — create entries from YAML only\n    for (const [file, meta] of yamlAssetMap) {\n      const ext = extname(file).toLowerCase().replace('.', '');\n      assets.push({\n        id: meta.id,\n        file,\n        purpose: meta.purpose,\n        format: ext,\n        filePath: join(assetsDir, file),\n      });\n    }\n  }\n\n  return assets;\n}\n\n/**\n * List all files in a directory (non-recursive for flat directories,\n * but uses walkDir for nested cases) matching given extensions.\n * Files whose relative path from `rootDir` starts with any ignore prefix are skipped.\n */\nfunction listFiles(\n  dir: string,\n  extensions: string[],\n  ignore: string[],\n  rootDir: string,\n): string[] {\n  const results: string[] = [];\n  walkDir(dir, extensions, ignore, rootDir, results);\n  return results;\n}\n\nfunction walkDir(\n  dir: string,\n  extensions: string[],\n  ignore: string[],\n  rootDir: string,\n  results: string[],\n): void {\n  let entries: string[];\n  try {\n    entries = readdirSync(dir);\n  } catch {\n    return;\n  }\n\n  for (const entry of entries) {\n    if (entry.startsWith('.')) continue;\n\n    const fullPath = join(dir, entry);\n\n    // Symlink containment check\n    let realPath: string;\n    try {\n      realPath = realpathSync(fullPath);\n    } catch {\n      continue; // broken symlink\n    }\n\n    let realRoot: string;\n    try {\n      realRoot = realpathSync(rootDir);\n    } catch {\n      realRoot = rootDir;\n    }\n\n    if (realPath !== realRoot && !realPath.startsWith(realRoot + sep)) {\n      continue; // symlink escape\n    }\n\n    // Check ignore list against relative path from rootDir\n    const relPath = relative(rootDir, fullPath).replace(/\\\\/g, '/');\n    if (ignore.some((prefix) => relPath === prefix || relPath.startsWith(prefix))) {\n      continue;\n    }\n\n    let stat;\n    try {\n      stat = statSync(fullPath);\n    } catch {\n      continue;\n    }\n\n    if (stat.isDirectory()) {\n      walkDir(fullPath, extensions, ignore, rootDir, results);\n    } else if (stat.isFile()) {\n      const ext = extname(entry).toLowerCase();\n      if (extensions.includes(ext)) {\n        results.push(fullPath);\n      }\n    }\n  }\n}\n\nfunction isDirectory(p: string): boolean {\n  try {\n    return statSync(p).isDirectory();\n  } catch {\n    return false;\n  }\n}\n","/**\n * @file verbal-parser.ts\n * @description Parses verbal/agent markdown documents with optional YAML frontmatter.\n */\n\nimport matter from 'gray-matter';\nimport { readFileSync, existsSync } from 'fs';\nimport type { VerbalDoc } from '../types/design-system.js';\n\n/**\n * Parse a verbal/agent markdown document with frontmatter support.\n * @param path - Absolute path to the markdown file\n * @returns Parsed verbal document or undefined if file doesn't exist\n */\nexport function parseVerbalDoc(path: string): VerbalDoc | undefined {\n  if (!existsSync(path)) return undefined;\n  let raw: string;\n  try {\n    raw = readFileSync(path, 'utf-8');\n  } catch {\n    return undefined;\n  }\n  // Tolerance principle: malformed frontmatter must not abort the scan.\n  // Fall back to treating the whole file as body with empty frontmatter.\n  let data: Record<string, unknown> = {};\n  let content = raw;\n  try {\n    const parsed = matter(raw);\n    data = parsed.data as Record<string, unknown>;\n    content = parsed.content;\n  } catch {\n    // keep defaults: empty frontmatter, full raw body\n  }\n  return {\n    frontmatter: data,\n    body: content.trim(),\n    source: path,\n  };\n}\n","/**\n * @file yaml-parser.ts\n * @description Tolerant YAML parser that gracefully handles malformed input\n * and missing files without throwing.\n */\n\nimport { readFileSync } from 'fs';\nimport { load } from 'js-yaml';\n\nexport interface YamlParseResult {\n  data: unknown;\n  warnings: string[];\n  source: string;\n}\n\n/**\n * Parse a YAML file with tolerance for missing or malformed input.\n * @param path - Absolute path to the YAML file\n * @returns Parse result with data, warnings, and source metadata\n */\nexport function parseYamlFile(path: string): YamlParseResult {\n  let text: string;\n  try {\n    text = readFileSync(path, 'utf-8');\n  } catch (err) {\n    return {\n      data: null,\n      warnings: [`Could not read YAML file: ${path} (${(err as Error).message})`],\n      source: path,\n    };\n  }\n\n  try {\n    const data = load(text);\n    return { data: data ?? null, warnings: [], source: path };\n  } catch (err) {\n    return {\n      data: null,\n      warnings: [`Invalid YAML in ${path}: ${(err as Error).message}`],\n      source: path,\n    };\n  }\n}\n","/**\n * @file motion-parser.ts\n * @description Parses motion.json and motion.css files together as a motion system.\n * Tolerant: handles missing or malformed files gracefully.\n */\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\n\nexport interface MotionParseResult {\n  tokens: unknown;\n  css: string;\n  warnings: string[];\n  source: string;\n}\n\n/**\n * Parse a motion system directory containing motion.json and motion.css.\n * @param dir - Absolute path to the directory containing motion files\n * @returns Parse result with tokens, CSS, warnings, and source metadata\n */\nexport function parseMotionDir(dir: string): MotionParseResult {\n  const warnings: string[] = [];\n  const jsonPath = join(dir, 'motion.json');\n  const cssPath = join(dir, 'motion.css');\n\n  let tokens: unknown = null;\n  if (existsSync(jsonPath)) {\n    try {\n      tokens = JSON.parse(readFileSync(jsonPath, 'utf-8'));\n    } catch (err) {\n      warnings.push(`Invalid motion.json: ${(err as Error).message}`);\n    }\n  } else {\n    warnings.push(`No motion.json found in ${dir}`);\n  }\n\n  let css = '';\n  if (existsSync(cssPath)) {\n    try {\n      css = readFileSync(cssPath, 'utf-8');\n    } catch (err) {\n      warnings.push(`Could not read motion.css: ${(err as Error).message}`);\n    }\n  }\n\n  return { tokens, css, warnings, source: dir };\n}\n","/**\n * @file markdown-parser.ts\n * @description Parses markdown files to extract guidelines, component specifications,\n * color palette documentation, typography docs, and brand voice content.\n * Supports YAML frontmatter via gray-matter.\n */\n\nimport matter from 'gray-matter';\nimport { readFileSync } from 'fs';\nimport { basename, extname } from 'path';\nimport type { DesignGuideline, DesignComponent, DesignColor, BrandContext, TokenSpecimen } from '../types/design-system.js';\n\n/**\n * Parses a markdown file as a design guideline.\n * @param filePath - Absolute path to the markdown file\n * @param context - Design context\n * @returns Parsed guideline with title, content, and section metadata\n */\nexport function parseGuidelineMarkdown(filePath: string, context: BrandContext): DesignGuideline {\n  let raw: string;\n  try {\n    raw = readFileSync(filePath, 'utf-8');\n  } catch {\n    console.error(`[markdown-parser] Could not read file: ${filePath}`);\n    return { title: basename(filePath, extname(filePath)), content: '', context, source: filePath };\n  }\n\n  const { data: frontmatter, content } = matter(raw);\n\n  const title =\n    (frontmatter.title as string) ??\n    extractFirstHeading(content) ??\n    basename(filePath, extname(filePath));\n\n  const section =\n    (frontmatter.section as string) ?? inferSectionFromPath(filePath);\n\n  return {\n    title,\n    content: content.trim(),\n    section,\n    context,\n    source: filePath,\n  };\n}\n\n/**\n * Parses a markdown file as component documentation.\n * Extracts component name, description, variants, and specs from heading structure.\n * @param filePath - Absolute path to the markdown file\n * @param context - Design context\n * @returns Array of parsed components\n */\nexport function parseComponentMarkdown(filePath: string, context: BrandContext): DesignComponent[] {\n  let raw: string;\n  try {\n    raw = readFileSync(filePath, 'utf-8');\n  } catch {\n    console.error(`[markdown-parser] Could not read file: ${filePath}`);\n    return [];\n  }\n\n  const { data: frontmatter, content } = matter(raw);\n\n  const name =\n    (frontmatter.name as string) ??\n    extractFirstHeading(content) ??\n    basename(filePath, extname(filePath));\n\n  const category = (frontmatter.category as string) ?? inferCategoryFromName(name);\n  const variants = (frontmatter.variants as string[]) ?? extractVariantsFromContent(content);\n  const description = extractDescription(content);\n\n  const component: DesignComponent = {\n    name,\n    category,\n    description,\n    variants,\n    usage: extractSection(content, 'Usage') ?? extractSection(content, 'Usage Guidelines'),\n    examples: extractCodeBlocks(content),\n    context,\n    source: filePath,\n  };\n\n  return [component];\n}\n\n/**\n * Parses a markdown file as color palette documentation.\n * Extracts color names, hex values, and usage notes from structured content.\n * @param filePath - Absolute path to the markdown file\n * @param context - Design context\n * @returns Array of DesignColor objects\n */\nexport function parsePaletteMarkdown(filePath: string, context: BrandContext): DesignColor[] {\n  let raw: string;\n  try {\n    raw = readFileSync(filePath, 'utf-8');\n  } catch {\n    console.error(`[markdown-parser] Could not read file: ${filePath}`);\n    return [];\n  }\n\n  const { content } = matter(raw);\n  const colors: DesignColor[] = [];\n\n  // Match hex values with their labels\n  const hexRe = /([\\w\\s-]+?):\\s*(#[0-9a-fA-F]{3,8})/g;\n  let match: RegExpExecArray | null;\n  while ((match = hexRe.exec(content)) !== null) {\n    const name = match[1].trim();\n    const value = match[2];\n    colors.push({\n      name,\n      token: `--color-${name.toLowerCase().replace(/\\s+/g, '-')}`,\n      value,\n      hex: value,\n      context,\n      source: filePath,\n    });\n  }\n\n  // Also look for table rows: | name | #hex | description |\n  const tableRowRe = /\\|\\s*([^|]+?)\\s*\\|\\s*(#[0-9a-fA-F]{3,8})\\s*\\|\\s*([^|]*?)\\s*\\|/g;\n  while ((match = tableRowRe.exec(content)) !== null) {\n    const name = match[1].trim();\n    if (name.toLowerCase() === 'name' || name.startsWith('---')) continue;\n    const value = match[2];\n    const usage = match[3]?.trim();\n    colors.push({\n      name,\n      token: `--color-${name.toLowerCase().replace(/\\s+/g, '-')}`,\n      value,\n      hex: value,\n      usage,\n      context,\n      source: filePath,\n    });\n  }\n\n  return colors;\n}\n\n/**\n * Infers a guideline section label from a file path.\n * e.g., agent/verbal/voice.md -> \"voice\"\n */\nexport function inferSectionFromPath(filePath: string): string {\n  const base = basename(filePath, extname(filePath));\n  return base.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Escape special regex characters in a string so it can be safely\n * interpolated into a RegExp pattern.\n */\nfunction escapeRegExp(str: string): string {\n  return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction extractFirstHeading(content: string): string | undefined {\n  const match = content.match(/^#+\\s+(.+)$/m);\n  return match ? match[1].trim() : undefined;\n}\n\nfunction extractDescription(content: string): string {\n  const lines = content.split('\\n');\n  const descLines: string[] = [];\n  let pastHeading = false;\n\n  for (const line of lines) {\n    if (/^#+\\s/.test(line)) {\n      if (pastHeading) break;\n      pastHeading = true;\n      continue;\n    }\n    if (pastHeading && line.trim()) {\n      descLines.push(line.trim());\n    }\n    if (descLines.length >= 3) break;\n  }\n\n  return descLines.join(' ');\n}\n\nfunction extractSection(content: string, heading: string): string | undefined {\n  const escaped = escapeRegExp(heading);\n  // Terminate at the next `## ` heading or true end-of-string. A bare `$`\n  // with the m flag matches every line end and truncates the capture;\n  // `^##\\s` (not `\\n##\\s`) keeps an empty section empty when two headings\n  // are adjacent with no blank line between them.\n  const re = new RegExp(`^##\\\\s+${escaped}\\\\b[^\\\\n]*\\\\n([\\\\s\\\\S]*?)(?=^##\\\\s|$(?![\\\\s\\\\S]))`, 'mi');\n  const match = re.exec(content);\n  return match ? match[1].trim() : undefined;\n}\n\nfunction extractCodeBlocks(content: string): string[] {\n  const blocks: string[] = [];\n  const re = /```[\\w]*\\n([\\s\\S]*?)```/g;\n  let match: RegExpExecArray | null;\n  while ((match = re.exec(content)) !== null) {\n    blocks.push(match[1].trim());\n  }\n  return blocks;\n}\n\nfunction inferCategoryFromName(name: string): string {\n  const lower = name.toLowerCase();\n  if (/button/.test(lower)) return 'actions';\n  if (/input|form|select|checkbox|radio/.test(lower)) return 'forms';\n  if (/card|modal|dialog|drawer/.test(lower)) return 'containers';\n  if (/nav|menu|tab|breadcrumb/.test(lower)) return 'navigation';\n  if (/heading|text|paragraph|label/.test(lower)) return 'typography';\n  if (/icon|avatar|badge|image/.test(lower)) return 'media';\n  return 'general';\n}\n\nfunction extractVariantsFromContent(content: string): string[] {\n  const variants: string[] = [];\n  const re = /^###\\s+(.+)$/gm;\n  let match: RegExpExecArray | null;\n  while ((match = re.exec(content)) !== null) {\n    variants.push(match[1].trim());\n  }\n  return variants;\n}\n\n// ---------------------------------------------------------------------------\n// v2 — Token specimens\n// ---------------------------------------------------------------------------\n\nexport interface TokenSpecimenResult {\n  specimen: TokenSpecimen | null;\n  warnings: string[];\n}\n\n/**\n * Parse a token specimen markdown file with required frontmatter.\n * @param filePath - Absolute path to the token specimen markdown file\n * @returns Parse result with specimen, warnings\n */\nexport function parseTokenSpecimen(filePath: string): TokenSpecimenResult {\n  const warnings: string[] = [];\n  let raw: string;\n  try {\n    raw = readFileSync(filePath, 'utf-8');\n  } catch {\n    return { specimen: null, warnings: [`Could not read ${filePath}`] };\n  }\n  const { data, content } = matter(raw);\n  const name = data.name as string | undefined;\n  const type = data.type as string | undefined;\n  // value may legitimately be falsy (0, false) — check presence, not truthiness.\n  const hasValue = data.value !== undefined && data.value !== null;\n  if (!name || !hasValue || !type) {\n    warnings.push(\n      `Token specimen at ${filePath} missing required frontmatter (name/value/type); skipping`,\n    );\n    return { specimen: null, warnings };\n  }\n  // YAML parses bare numbers/booleans to non-strings; TokenSpecimen.value is a string.\n  const value = String(data.value);\n  return {\n    specimen: {\n      name,\n      value,\n      type,\n      role: data.role as string | undefined,\n      related: data.related as string[] | undefined,\n      body: content.trim(),\n      source: filePath,\n    },\n    warnings,\n  };\n}\n","/**\n * @file css-parser.ts\n * @description Parses CSS files to extract design tokens (custom properties),\n * class names, font-face declarations, and media queries using the css-tree library.\n */\n\nimport * as csstree from 'css-tree';\nimport { readFileSync } from 'fs';\nimport type { DesignColor, DesignTypographyItem, DesignCSSFile, BrandContext } from '../types/design-system.js';\n\n/** Regular expression to detect CSS color values, including modern color functions. */\nconst COLOR_RE =\n  /^(#[0-9a-f]{3,8}|rgb\\(|rgba\\(|hsl\\(|hsla\\(|hwb\\(|lab\\(|lch\\(|oklab\\(|oklch\\(|color\\(|color-mix\\(|aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgr[ae]y|darkgreen|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategr[ae]y|darkturquoise|darkviolet|deeppink|deepskyblue|dimgr[ae]y|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gr[ae]y|green|greenyellow|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgr[ae]y|lightgreen|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategr[ae]y|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategr[ae]y|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)/i;\n\n/** Regular expression to detect typography-related CSS token names. */\nconst TYPO_TOKEN_RE = /font|type|text|heading|body|display|caption|label|title|letter-spacing|line-height/i;\n\n/**\n * Parses a CSS file and extracts all custom properties and class definitions.\n * @param filePath - Absolute path to the CSS file\n * @param context - Which design context this file belongs to\n * @returns Parsed CSS file with custom properties and extracted design tokens\n */\nexport function parseCSSFile(filePath: string, _context: BrandContext): DesignCSSFile {\n  let rawContent: string;\n  try {\n    rawContent = readFileSync(filePath, 'utf-8');\n  } catch {\n    console.error(`[css-parser] Could not read file: ${filePath}`);\n    return { filePath, rawContent: '', customProperties: {}, classes: [] };\n  }\n\n  const customProperties: Record<string, string> = {};\n  const classes: string[] = [];\n\n  try {\n    const ast = csstree.parse(rawContent, { parseCustomProperty: true });\n\n    csstree.walk(ast, {\n      visit: 'Declaration',\n      enter(node) {\n        if (node.property.startsWith('--')) {\n          const value = csstree.generate(node.value);\n          customProperties[node.property] = value;\n        }\n      },\n    });\n\n    csstree.walk(ast, {\n      visit: 'ClassSelector',\n      enter(node) {\n        if (!classes.includes(node.name)) {\n          classes.push(node.name);\n        }\n      },\n    });\n  } catch {\n    // Fallback: regex-based extraction for files css-tree can't parse\n    const propRe = /(--[\\w-]+)\\s*:\\s*([^;]+);/g;\n    let match: RegExpExecArray | null;\n    while ((match = propRe.exec(rawContent)) !== null) {\n      customProperties[match[1]] = match[2].trim();\n    }\n  }\n\n  return { filePath, rawContent, customProperties, classes };\n}\n\n/**\n * Attempts to interpret CSS custom properties as color tokens.\n * Detects color values (#hex, rgb(), hsl(), named colors).\n * @param customProperties - Map of token name to value\n * @param context - Design context\n * @param source - File path source\n * @returns Array of DesignColor objects for properties that contain color values\n */\nexport function extractColorsFromCSS(\n  customProperties: Record<string, string>,\n  context: BrandContext,\n  source: string,\n): DesignColor[] {\n  const colors: DesignColor[] = [];\n\n  for (const [token, value] of Object.entries(customProperties)) {\n    if (!COLOR_RE.test(value.trim())) continue;\n\n    const name = tokenToName(token);\n    const role = inferColorRole(token);\n    const hex = normalizeToHex(value.trim());\n\n    colors.push({ name, token, value: value.trim(), hex, role, context, source });\n  }\n\n  return colors;\n}\n\n/**\n * Attempts to interpret CSS custom properties as typography tokens.\n * Detects font-family, font-size, font-weight, line-height tokens.\n * @param customProperties - Map of token name to value\n * @param context - Design context\n * @param source - File path source\n * @returns Array of DesignTypographyItem objects for typography properties\n */\nexport function extractTypographyFromCSS(\n  customProperties: Record<string, string>,\n  context: BrandContext,\n  source: string,\n): DesignTypographyItem[] {\n  const items: DesignTypographyItem[] = [];\n\n  for (const [token, value] of Object.entries(customProperties)) {\n    if (!TYPO_TOKEN_RE.test(token)) continue;\n\n    const name = tokenToName(token);\n    const item: DesignTypographyItem = { name, token, context, source };\n\n    if (/font-family/i.test(token)) {\n      item.fontFamily = value;\n    } else if (/font-size/i.test(token)) {\n      item.fontSize = value;\n    } else if (/font-weight/i.test(token)) {\n      item.fontWeight = value;\n    } else if (/line-height/i.test(token)) {\n      item.lineHeight = value;\n    } else if (/letter-spacing/i.test(token)) {\n      item.letterSpacing = value;\n    } else {\n      // Generic typography token\n      item.fontSize = value;\n    }\n\n    items.push(item);\n  }\n\n  return items;\n}\n\n/**\n * Converts a CSS custom property name to a human-readable name.\n * e.g. \"--color-primary-blue\" -> \"Primary Blue\"\n */\nfunction tokenToName(token: string): string {\n  return token\n    .replace(/^--/, '')\n    .replace(/[-_]+/g, ' ')\n    .replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Infers a semantic color role from a CSS custom property name.\n */\nfunction inferColorRole(token: string): string | undefined {\n  const lower = token.toLowerCase();\n  if (lower.includes('primary')) return 'primary';\n  if (lower.includes('secondary')) return 'secondary';\n  if (lower.includes('accent')) return 'accent';\n  if (lower.includes('neutral') || lower.includes('gray') || lower.includes('grey')) return 'neutral';\n  if (lower.includes('error') || lower.includes('danger') || lower.includes('destructive')) return 'error';\n  if (lower.includes('success')) return 'success';\n  if (lower.includes('warning')) return 'warning';\n  if (lower.includes('info')) return 'info';\n  return undefined;\n}\n\n/**\n * Attempts to normalize a CSS color value to a hex string.\n * Valid hex lengths: 3 (#rgb), 4 (#rgba), 6 (#rrggbb), 8 (#rrggbbaa).\n * Returns undefined if normalization isn't possible.\n */\nexport function normalizeToHex(value: string): string | undefined {\n  const hexMatch = value.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);\n  if (hexMatch) {\n    const hex = hexMatch[1];\n    if (hex.length === 3 || hex.length === 4) {\n      return `#${[...hex].map((c) => c + c).join('')}`;\n    }\n    return `#${hex}`;\n  }\n  return undefined;\n}\n\n","/**\n * @file font-parser.ts\n * @description Catalogs web font files (.woff2, .otf, .ttf, .woff) in the design system.\n * Extracts font family and weight metadata from filenames and metadata.\n */\n\nimport { basename, extname } from 'path';\nimport type { DesignFont } from '../types/design-system.js';\n\n/** Maps common weight names to numeric values. */\nconst WEIGHT_MAP: Record<string, number> = {\n  thin: 100,\n  hairline: 100,\n  extralight: 200,\n  ultralight: 200,\n  light: 300,\n  regular: 400,\n  normal: 400,\n  medium: 500,\n  semibold: 600,\n  demibold: 600,\n  bold: 700,\n  extrabold: 800,\n  ultrabold: 800,\n  black: 900,\n  heavy: 900,\n};\n\n/**\n * Parses a font file and extracts metadata.\n * Infers family name, weight, and style from the filename.\n * e.g., \"inter-700-normal.woff2\" -> family: Inter, weight: 700, style: normal\n * @param filePath - Absolute path to the font file\n * @returns DesignFont metadata\n */\nexport function parseFontFile(filePath: string): DesignFont {\n  const ext = extname(filePath).toLowerCase().replace('.', '');\n  const name = basename(filePath, extname(filePath));\n\n  const format = ext as DesignFont['format'];\n  const parts = name.split(/[-_]+/);\n\n  let family = '';\n  let weight: string | number | undefined;\n  let style: 'normal' | 'italic' = 'normal';\n\n  const familyParts: string[] = [];\n\n  for (const part of parts) {\n    const lower = part.toLowerCase();\n\n    if (lower === 'italic' || lower === 'oblique') {\n      style = 'italic';\n      continue;\n    }\n\n    if (lower === 'normal' || lower === 'regular') {\n      continue;\n    }\n\n    const numWeight = parseInt(lower, 10);\n    if (!isNaN(numWeight) && numWeight >= 100 && numWeight <= 900) {\n      weight = numWeight;\n      continue;\n    }\n\n    if (WEIGHT_MAP[lower] !== undefined) {\n      weight = WEIGHT_MAP[lower];\n      continue;\n    }\n\n    familyParts.push(part.charAt(0).toUpperCase() + part.slice(1));\n  }\n\n  family = familyParts.join(' ') || 'Unknown';\n  weight = weight ?? 400;\n\n  return { family, weight, style, filePath, format };\n}\n\n/**\n * Infers font weight from a filename component.\n * Handles numeric weights (400, 700) and named weights (regular, bold, light, etc.)\n * @param filename - Filename or filename segment\n * @returns Numeric weight or undefined\n */\nexport function inferFontWeight(filename: string): string | number | undefined {\n  const lower = filename.toLowerCase();\n\n  const num = parseInt(lower, 10);\n  if (!isNaN(num) && num >= 100 && num <= 900) return num;\n\n  for (const [name, value] of Object.entries(WEIGHT_MAP)) {\n    if (lower.includes(name)) return value;\n  }\n\n  return undefined;\n}\n\n","/**\n * @file context-resolver.ts\n * @description v2 context resolution engine for BrandKit MCP.\n *\n * Merges the base visual layer with web or product artifact overrides to produce\n * a fully resolved ResolvedDesignSystem for each BrandContext (base, web, product).\n *\n * Merge rules:\n * 1. For base: return base data as-is.\n * 2. For web/product: overlay overrides on base. If a piece exists in the override,\n *    the override wins; otherwise fall through to base.\n * 3. Component/token/asset/font arrays: override item with the same key replaces the\n *    base item; items only in base carry forward; items only in override are added.\n * 4. colorsAndType + motion are single objects — override wins if present, else base.\n *\n * Note: v2 TokenSpecimen[] is stored on ResolvedDesignSystem.tokens but NOT mapped\n * into .colors/.typography. Downstream get_tokens tools read from the raw index.\n * Similarly, motion is not surfaced here — get_motion reads from the raw index.\n *\n * Note: v2 assets (logos, textures, etc.) are folded into .textures; get_assets\n * surfaces them to callers.\n */\n\nimport type {\n  BrandContext,\n  ResolvedDesignSystem,\n  AssetInventory,\n  DesignColor,\n  DesignTypographyItem,\n  DesignTexture,\n  DesignLogoSystem,\n  DesignFont,\n  DesignCSSFile,\n  AssetEntry,\n  FontFace,\n  DesignComponent,\n  TokenSpecimen,\n} from './types/design-system.js';\nimport type { RawContextData } from './indexer/types.js';\nimport type { ScanResult } from './scanner/directory-scanner.js';\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface ResolveOptions {\n  brandName: string;\n  brandDescription?: string;\n}\n\n/**\n * Resolves all three contexts (base, web, product) from a ScanResult.\n * Returns a record keyed by BrandContext, each containing a fully resolved\n * ResolvedDesignSystem.\n */\nexport function resolveAll(\n  scan: ScanResult,\n  opts: ResolveOptions,\n): Record<BrandContext, ResolvedDesignSystem> {\n  return {\n    base: materialize(scan.base, 'base', opts),\n    web: materialize(mergeContext(scan.base, scan.web), 'web', opts),\n    product: materialize(mergeContext(scan.base, scan.product), 'product', opts),\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Merge helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Merges two arrays using a key function. Override items replace base items\n * with the same key; remaining base items are preserved; override-only items\n * are appended.\n */\nfunction mergeByKey<T>(base: T[], override: T[], keyFn: (item: T) => string): T[] {\n  const map = new Map<string, T>();\n  for (const item of base) {\n    map.set(keyFn(item), item);\n  }\n  for (const item of override) {\n    map.set(keyFn(item), item);\n  }\n  return Array.from(map.values());\n}\n\n/**\n * Merges two RawContextData objects: override wins on single-object fields\n * (colorsAndType, motion); arrays are merged by key.\n */\nfunction mergeContext(base: RawContextData, override: RawContextData): RawContextData {\n  return {\n    colorsAndType: override.colorsAndType ?? base.colorsAndType,\n    components: mergeByKey(\n      base.components,\n      override.components,\n      (c) => c.name.toLowerCase(),\n    ),\n    tokens: mergeByKey(base.tokens, override.tokens, (t) => t.name),\n    assets: mergeByKey(\n      base.assets,\n      override.assets,\n      (a) => a.id ?? a.file,\n    ),\n    fonts: mergeByKey(\n      base.fonts,\n      override.fonts,\n      (f) => `${f.family}:${f.weight ?? ''}:${f.style ?? ''}`,\n    ),\n    motion: override.motion ?? base.motion,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// CSS custom property extraction\n// ---------------------------------------------------------------------------\n\n/** Token name patterns that indicate a color. */\nconst COLOR_TOKEN_RE = /^--color-/i;\n\n/** Matches common CSS color value formats. */\nconst COLOR_VALUE_RE =\n  /^(#[0-9a-f]{3,8}|rgb\\(|rgba\\(|hsl\\(|hsla\\(|hwb\\(|lab\\(|lch\\(|oklab\\(|oklch\\(|color\\()/i;\n\n/** Token name patterns that indicate a typography value. */\nconst TYPO_TOKEN_RE =\n  /^--(font-|type-|text-|heading|body|display|caption|label|title|letter-spacing|line-height)/i;\n\n/**\n * Derives a human-readable name from a CSS custom property token.\n * \"--color-primary-500\" → \"Color Primary 500\"\n */\nfunction tokenToName(token: string): string {\n  return token\n    .replace(/^--/, '')\n    .replace(/-/g, ' ')\n    .replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Extracts DesignColor entries from a CSS file's custom properties.\n * A property is treated as a color if its name starts with --color- OR its\n * value looks like a CSS color literal.\n */\nfunction extractColors(css: DesignCSSFile, ctx: BrandContext): DesignColor[] {\n  const colors: DesignColor[] = [];\n  for (const [token, value] of Object.entries(css.customProperties)) {\n    if (COLOR_TOKEN_RE.test(token) || COLOR_VALUE_RE.test(value.trim())) {\n      colors.push({\n        name: tokenToName(token),\n        token,\n        value: value.trim(),\n        context: ctx,\n        source: css.filePath,\n      });\n    }\n  }\n  return colors;\n}\n\n/**\n * Extracts DesignTypographyItem entries from a CSS file's custom properties.\n * Properties whose name matches common typography token patterns are included.\n */\nfunction extractTypography(css: DesignCSSFile, ctx: BrandContext): DesignTypographyItem[] {\n  const items: DesignTypographyItem[] = [];\n  for (const [token, value] of Object.entries(css.customProperties)) {\n    if (!TYPO_TOKEN_RE.test(token)) continue;\n    const item: DesignTypographyItem = {\n      name: tokenToName(token),\n      token,\n      context: ctx,\n      source: css.filePath,\n    };\n    const lower = token.toLowerCase();\n    const trimmed = value.trim();\n    if (lower.includes('font-family') || lower.includes('font-display') || lower.includes('font-body')) {\n      item.fontFamily = trimmed;\n    } else if (lower.includes('letter-spacing') || lower.includes('tracking')) {\n      item.letterSpacing = trimmed;\n    } else if (lower.includes('line-height')) {\n      item.lineHeight = trimmed;\n    } else if (lower.includes('text-transform')) {\n      item.textTransform = trimmed;\n    } else if (lower.includes('font-size') || lower.includes('size')) {\n      item.fontSize = trimmed;\n    } else if (lower.includes('font-weight') || lower.includes('weight')) {\n      item.fontWeight = trimmed;\n    } else if (/(^|-)line(-|$)/.test(lower)) {\n      item.lineHeight = trimmed;\n    }\n    items.push(item);\n  }\n  return items;\n}\n\n// ---------------------------------------------------------------------------\n// Asset → Texture mapping\n// ---------------------------------------------------------------------------\n\nfunction assetToTexture(entry: AssetEntry, ctx: BrandContext): DesignTexture {\n  return {\n    name: entry.id ?? entry.file,\n    filePath: entry.filePath,\n    format: entry.format,\n    usage: entry.purpose,\n    context: ctx,\n    source: entry.filePath,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Font mapping\n// ---------------------------------------------------------------------------\n\nfunction fontFaceToDesignFont(face: FontFace): DesignFont {\n  return {\n    family: face.family,\n    weight: face.weight,\n    style: face.style,\n    filePath: face.filePath,\n    format: face.format,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Inventory builder\n// ---------------------------------------------------------------------------\n\nfunction buildInventory(ds: Omit<ResolvedDesignSystem, 'assetInventory'>): AssetInventory {\n  return {\n    totalFiles:\n      ds.colors.length +\n      ds.typography.length +\n      (ds.logos.variants?.length ?? 0) +\n      ds.components.length +\n      ds.textures.length +\n      ds.guidelines.length +\n      ds.cssFiles.length +\n      ds.fonts.length +\n      ds.pdfTexts.length,\n    colors: ds.colors.length,\n    typography: ds.typography.length,\n    logos: ds.logos.variants?.length ?? 0,\n    components: ds.components.length,\n    textures: ds.textures.length,\n    guidelines: ds.guidelines.length,\n    cssFiles: ds.cssFiles.length,\n    fonts: ds.fonts.length,\n    pdfs: ds.pdfTexts.length,\n  };\n}\n\nconst EMPTY_LOGO_SYSTEM: DesignLogoSystem = { variants: [] };\n\n// ---------------------------------------------------------------------------\n// Materialize: RawContextData → ResolvedDesignSystem\n// ---------------------------------------------------------------------------\n\n/**\n * Converts merged RawContextData into a ResolvedDesignSystem.\n *\n * colorsAndType.customProperties are split into .colors and .typography by\n * token-name heuristics. assets are bridged to .textures; tokens are kept on\n * .tokens but not mapped into colors/typography — downstream tooling reads\n * from the raw index. motion is not surfaced here.\n */\nfunction materialize(\n  raw: RawContextData,\n  ctx: BrandContext,\n  opts: ResolveOptions,\n): ResolvedDesignSystem {\n  const colors: DesignColor[] = raw.colorsAndType\n    ? extractColors(raw.colorsAndType, ctx)\n    : [];\n\n  const typography: DesignTypographyItem[] = raw.colorsAndType\n    ? extractTypography(raw.colorsAndType, ctx)\n    : [];\n\n  const components: DesignComponent[] = raw.components.map((c) => ({\n    ...c,\n    context: ctx,\n  }));\n\n  const textures: DesignTexture[] = raw.assets.map((a) => assetToTexture(a, ctx));\n\n  const fonts: DesignFont[] = raw.fonts.map(fontFaceToDesignFont);\n\n  const tokens: TokenSpecimen[] = raw.tokens;\n\n  // cssFiles: expose colorsAndType CSS file (motion.css is not surfaced here)\n  const cssFiles: DesignCSSFile[] = raw.colorsAndType ? [raw.colorsAndType] : [];\n\n  const partial = {\n    name: opts.brandName,\n    description: opts.brandDescription,\n    context: ctx,\n    colors,\n    typography,\n    logos: EMPTY_LOGO_SYSTEM,\n    components,\n    textures,\n    guidelines: [],\n    fonts,\n    cssFiles,\n    pdfTexts: [],\n    tokens,\n  };\n\n  return {\n    ...partial,\n    assetInventory: buildInventory(partial),\n  };\n}\n\n","/**\n * @file index.ts\n * @description Design System Indexer -- orchestrates v2 scanner + resolver to build a\n * complete in-memory index of the design system.\n *\n * Scans the brand_atomic_system directory via scanBrandRoot, resolves contexts\n * via resolveAll, and assembles the results into a DesignSystemIndex.\n */\n\nimport { resolve, dirname } from 'path';\nimport type { BrandKitConfig } from '../types/config.js';\nimport type { DesignSystemIndex } from './types.js';\nimport { loadConfigWithPath } from '../config/loader.js';\nimport { scanBrandRoot } from '../scanner/directory-scanner.js';\nimport { resolveAll } from '../context-resolver.js';\n\n/**\n * Convenience wrapper: loads a config file by path, scans the brand root, and\n * returns the complete DesignSystemIndex.\n *\n * @param configPath - Absolute or relative path to brandkit.config.yaml\n */\nexport async function buildIndex(configPath: string): Promise<DesignSystemIndex> {\n  const { config, filePath } = loadConfigWithPath(configPath);\n  const brandRoot = resolve(dirname(filePath), config.brand.root);\n  return buildDesignSystemIndex(config, brandRoot);\n}\n\n/**\n * Builds the complete design system index from a loaded BrandKitConfig.\n * This is the main entry point called by the MCP server on startup\n * and when file changes are detected (hot reload).\n *\n * @param config - Loaded and path-resolved BrandKit config\n * @param brandRootOverride - Optional override for the brand root directory.\n *   When omitted, falls back to config.brand.root (which must already be\n *   an absolute path if the caller used resolveConfigPaths).\n * @returns The complete design system index\n */\nexport async function buildDesignSystemIndex(\n  config: BrandKitConfig,\n  brandRootOverride?: string,\n): Promise<DesignSystemIndex> {\n  const brandRoot = brandRootOverride ?? config.brand.root;\n\n  const scan = scanBrandRoot(brandRoot, { ignore: config.ignore });\n  const resolved = resolveAll(scan, {\n    brandName: config.brand.name,\n    brandDescription: config.brand.description,\n  });\n\n  return {\n    brandName: config.brand.name,\n    brandDescription: config.brand.description,\n    brandRoot,\n    lastIndexed: new Date(),\n    magicTrick: scan.magicTrick,\n    verbal: scan.verbal,\n    base: scan.base,\n    web: scan.web,\n    product: scan.product,\n    resolved,\n    warnings: scan.warnings,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports retained for downstream callers that import from this module\n// ---------------------------------------------------------------------------\n\nexport type { DesignSystemIndex } from './types.js';\nexport type { SearchIndexEntry } from './types.js';\n\n/**\n * Performs full-text search across the search index.\n * @param query - Search query string\n * @param entries - Array of search index entries\n * @param limit - Maximum results to return\n * @param context - Optional context filter\n * @returns Matching entries with relevance scores and snippets\n */\nimport type { SearchIndexEntry } from './types.js';\n\nexport function searchIndex(\n  query: string,\n  entries: SearchIndexEntry[],\n  limit: number = 10,\n  context?: string,\n): Array<SearchIndexEntry & { score: number; snippet: string }> {\n  const queryLower = query.toLowerCase();\n  const queryTerms = queryLower.split(/\\s+/).filter(Boolean);\n\n  const results: Array<SearchIndexEntry & { score: number; snippet: string }> = [];\n\n  for (const entry of entries) {\n    if (context && entry.context !== context) continue;\n\n    const contentLower = entry.content.toLowerCase();\n    let score = 0;\n\n    for (const term of queryTerms) {\n      const idx = contentLower.indexOf(term);\n      if (idx !== -1) {\n        score += 1;\n        if (entry.name.toLowerCase().includes(term)) score += 2;\n      }\n    }\n\n    if (score > 0) {\n      const snippetIdx = contentLower.indexOf(queryTerms[0]);\n      const snippetStart = Math.max(0, snippetIdx - 40);\n      const snippetEnd = Math.min(entry.content.length, snippetIdx + 120);\n      const snippet =\n        (snippetStart > 0 ? '...' : '') +\n        entry.content.slice(snippetStart, snippetEnd).trim() +\n        (snippetEnd < entry.content.length ? '...' : '');\n\n      results.push({ ...entry, score, snippet });\n    }\n  }\n\n  results.sort((a, b) => b.score - a.score);\n  return results.slice(0, limit);\n}\n","/**\n * @file commands/docs.ts\n * @description Implementation of the `brandkit-mcp docs` command.\n * Generates project documentation files: CLAUDE.md, AGENTS.md, SKILLS.md, and DESIGN.md.\n *\n * User content outside the branded delimiter block is preserved on\n * subsequent runs. Only the region between the start and end delimiters\n * is replaced; if no delimiters exist in an existing file the generated\n * block is appended so nothing is lost.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { loadConfigWithPath, resolveConfigPaths } from '../../config/loader.js';\nimport { buildDesignSystemIndex } from '../../indexer/index.js';\n\nconst DELIMITER_START = '<!-- brandkit-mcp:start -->';\nconst DELIMITER_END = '<!-- brandkit-mcp:end -->';\n\n/**\n * Write a generated block into a file while preserving any user content\n * that lives outside the delimiter markers.\n *\n * - If the file does not exist: create it with the delimited block.\n * - If the file exists and contains delimiters: replace only the\n *   delimited region.\n * - If the file exists but has no delimiters: append the block so\n *   existing user content is never overwritten.\n */\nfunction updateFileWithDelimiters(filePath: string, generatedBlock: string): void {\n  const wrappedBlock = `${DELIMITER_START}\\n${generatedBlock}\\n${DELIMITER_END}`;\n\n  if (!existsSync(filePath)) {\n    writeFileSync(filePath, wrappedBlock + '\\n', 'utf-8');\n    return;\n  }\n\n  const existing = readFileSync(filePath, 'utf-8');\n  const startIdx = existing.indexOf(DELIMITER_START);\n  const endIdx = existing.indexOf(DELIMITER_END);\n\n  if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {\n    // Replace the existing delimited block only\n    const updated =\n      existing.slice(0, startIdx) +\n      wrappedBlock +\n      existing.slice(endIdx + DELIMITER_END.length);\n    writeFileSync(filePath, updated, 'utf-8');\n  } else {\n    // No delimiters found -- append to preserve existing content\n    writeFileSync(filePath, existing.trimEnd() + '\\n\\n' + wrappedBlock + '\\n', 'utf-8');\n  }\n}\n\n/**\n * Handles the `brandkit-mcp docs` command.\n * Generates CLAUDE.md, AGENTS.md, SKILLS.md, and DESIGN.md from the design system.\n */\nexport async function docsCommand(options: { config?: string; output?: string }): Promise<void> {\n  console.log('Generating project documentation...\\n');\n\n  // Resolve relative paths against the config file's own directory (same\n  // portability fix as startServer in src/index.ts).\n  const { config: rawConfig, filePath } = loadConfigWithPath(options.config);\n  const config = resolveConfigPaths(rawConfig, dirname(filePath));\n  const index = await buildDesignSystemIndex(config);\n  const outputDir = options.output ?? process.cwd();\n\n  const brandName = config.brand.name;\n  const brandDescription = config.brand.description ?? 'N/A';\n\n  // Generate CLAUDE.md\n  const claudeBlock = `# ${brandName} Design System\n\n## Brand Overview\n\n- **Name**: ${brandName}\n- **Description**: ${brandDescription}\n- **Brand Root**: ${config.brand.root}\n\n## Asset Inventory (base context)\n\n| Category | Count |\n|---|---|\n| Tokens | ${index.base.tokens.length} |\n| Components | ${index.base.components.length} |\n| Fonts | ${index.base.fonts.length} |\n| Assets | ${index.base.assets.length} |\n| Motion | ${index.base.motion != null ? 'yes' : 'no'} |\n\n## Available MCP Tools (v2 surface)\n\nUse these tools to query the design system:\n- \\`get_brand_overview\\` -- High-level overview + taste primer\n- \\`get_magic_trick\\` -- Verbatim magic_trick.md\n- \\`get_positioning\\` -- Positioning document\n- \\`get_audience\\` -- Audience YAML, parsed\n- \\`get_messaging\\` -- Messaging document\n- \\`get_differentiation\\` -- Differentiation document\n- \\`get_concepts\\` -- Creative concepts/directions\n- \\`get_voice\\` -- Voice document\n- \\`get_colors_and_type\\` -- Colors + typography custom properties\n- \\`get_assets\\` -- Logos + brand assets\n- \\`get_fonts\\` -- Font faces\n- \\`get_components\\` -- UI primitives\n- \\`get_tokens\\` -- Token specimens\n- \\`get_motion\\` -- Motion system\n- \\`get_css\\` -- colors_and_type.css + motion.css text\n- \\`search_brand\\` -- Full-text search\n- \\`get_context_diff\\` -- Diff base vs web vs product\n- \\`validate_usage\\` -- Validate brand compliance`;\n\n  updateFileWithDelimiters(join(outputDir, 'CLAUDE.md'), claudeBlock);\n  console.log('[OK] Generated CLAUDE.md');\n\n  // Generate AGENTS.md\n  const agentsBlock = `# ${brandName} -- Agent Guidelines\n\n## Design System Rules\n\nWhen generating code or content for ${brandName}:\n\n1. Always load the brand overview first with \\`get_brand_overview\\`\n2. Use colors and typography via \\`get_colors_and_type\\`\n3. Follow the brand voice guidelines via \\`get_voice\\`\n4. Use the correct context: \"base\" (default), \"web\" for website, \"product\" for app\n5. Validate any design choices with \\`validate_usage\\`\n\n## Context Rules\n\n- **base**: Default shared assets (agent/visual/)\n- **web**: Web-specific overrides (agent/visual/artifacts/web/)\n- **product**: Product/app-specific overrides (agent/visual/artifacts/product/)`;\n\n  updateFileWithDelimiters(join(outputDir, 'AGENTS.md'), agentsBlock);\n  console.log('[OK] Generated AGENTS.md');\n\n  // Generate SKILLS.md\n  const skillsBlock = `# ${brandName} -- Skills Reference\n\n## Design System Query Skills\n\n### Get Brand Colors and Typography\n\\`\\`\\`\nTool: get_colors_and_type\nArgs: { \"context\": \"base\" }\n\\`\\`\\`\n\n### Get Voice Guidelines\n\\`\\`\\`\nTool: get_voice\n\\`\\`\\`\n\n### Search Design System\n\\`\\`\\`\nTool: search_brand\nArgs: { \"query\": \"button primary\", \"context\": \"base\" }\n\\`\\`\\`\n\n### Export Design Tokens\n\\`\\`\\`\nTool: get_tokens\nArgs: { \"context\": \"base\" }\n\\`\\`\\`\n\n### Compare Contexts\n\\`\\`\\`\nTool: get_context_diff\n\\`\\`\\``;\n\n  updateFileWithDelimiters(join(outputDir, 'SKILLS.md'), skillsBlock);\n  console.log('[OK] Generated SKILLS.md');\n\n  // Generate DESIGN.md\n  const tokenSummary = index.base.tokens.slice(0, 10)\n    .map((t) => `- **${t.name}**: \\`${t.value}\\``)\n    .join('\\n');\n\n  const componentSummary = index.base.components\n    .map((c) => `- **${c.name}**: ${c.description ?? 'No description'}`)\n    .join('\\n');\n\n  const assetSummary = index.base.assets.slice(0, 10)\n    .map((a) => `- **${a.file}** (${a.format})`)\n    .join('\\n');\n\n  const designBlock = `# ${brandName} -- Design System Reference\n\n## Tokens (base context)\n\n${tokenSummary || 'No tokens defined.'}\n\n## Components (base context)\n\n${componentSummary || 'No components defined.'}\n\n## Assets (base context)\n\n${assetSummary || 'No assets defined.'}`;\n\n  updateFileWithDelimiters(join(outputDir, 'DESIGN.md'), designBlock);\n  console.log('[OK] Generated DESIGN.md');\n\n  console.log('\\nAll documentation files generated successfully.');\n}\n","/**\n * @file commands/preview.ts\n * @description Implementation of the `brandkit-mcp preview` command.\n * Starts the local preview UI for browsing the brand atomic system.\n */\n\nimport { dirname } from 'path';\nimport { exec } from 'child_process';\nimport { loadConfigWithPath, resolveConfigPaths } from '../../config/loader.js';\nimport { buildDesignSystemIndex } from '../../indexer/index.js';\nimport { watchBrandDirectory } from '../../indexer/hot-reload.js';\nimport { createPreviewServer, type IndexRef } from '../../preview/server.js';\n\nexport interface PreviewOptions {\n  port?: string;\n  config?: string;\n  watch?: boolean;\n  open?: boolean;\n}\n\n/**\n * Handles the `brandkit-mcp preview` command.\n */\nexport async function previewCommand(options: PreviewOptions): Promise<void> {\n  // Resolve relative paths against the config file's own directory (same\n  // portability fix as startServer in src/index.ts).\n  const { config: rawConfig, filePath } = loadConfigWithPath(options.config);\n  const config = resolveConfigPaths(rawConfig, dirname(filePath));\n\n  console.log(`Building design system index for \"${config.brand.name}\"...`);\n  const ref: IndexRef = { current: await buildDesignSystemIndex(config) };\n\n  if (options.watch) {\n    console.log('File watching enabled');\n    watchBrandDirectory(config, (newIndex) => {\n      ref.current = newIndex;\n      console.log('Index updated');\n    });\n  }\n\n  const app = createPreviewServer(ref, config);\n  const parsed = parseInt(options.port ?? '', 10);\n  const port = Number.isNaN(parsed) ? config.preview.port : parsed;\n\n  const server = app.listen(port, () => {\n    const url = `http://localhost:${port}`;\n    console.log(`Preview running at ${url}`);\n    if (options.open) {\n      const opener =\n        process.platform === 'darwin' ? 'open'\n        : process.platform === 'win32' ? 'start \"\"'\n        : 'xdg-open';\n      exec(`${opener} ${url}`, () => {\n        // Best-effort: a failed browser launch is not an error.\n      });\n    }\n  });\n\n  server.on('error', (err: NodeJS.ErrnoException) => {\n    if (err.code === 'EADDRINUSE') {\n      console.error(`Port ${port} is already in use. Pass a different one with --port.`);\n    } else {\n      console.error('Preview server error:', err.message);\n    }\n    process.exit(1);\n  });\n}\n","/**\n * @file hot-reload.ts\n * @description File watcher for hot reload in dev mode.\n * Watches the brand directory for file changes and triggers re-indexing.\n * Uses chokidar for cross-platform file watching.\n */\n\nimport chokidar from 'chokidar';\nimport type { BrandKitConfig } from '../types/config.js';\nimport type { DesignSystemIndex } from './types.js';\nimport { buildDesignSystemIndex } from './index.js';\n\n/**\n * Serializes reindex executions: at most one reindex runs at a time. A\n * trigger that arrives mid-flight queues exactly one follow-up run, so the\n * final state always reflects the latest filesystem events (no\n * last-to-complete-wins race). Errors are logged, never thrown.\n * Exported for tests.\n */\nexport function createReindexRunner(\n  reindex: () => Promise<DesignSystemIndex>,\n  onUpdate: (index: DesignSystemIndex) => void,\n): () => Promise<void> {\n  let inFlight = false;\n  let rerunRequested = false;\n\n  const run = async (): Promise<void> => {\n    if (inFlight) {\n      rerunRequested = true;\n      return;\n    }\n    inFlight = true;\n    try {\n      onUpdate(await reindex());\n    } catch (err) {\n      console.error('[hot-reload] Re-indexing failed:', err);\n    } finally {\n      inFlight = false;\n      if (rerunRequested) {\n        rerunRequested = false;\n        void run();\n      }\n    }\n  };\n\n  return run;\n}\n\n/**\n * Starts watching the brand directory for changes.\n * Calls the provided callback with the updated index whenever files change.\n * Debounces rapid changes (e.g., saving multiple files at once).\n * @param config - BrandKit config\n * @param onUpdate - Callback invoked with the new index after re-indexing\n * @returns An async function that stops the watcher and resolves when closed\n */\nexport function watchBrandDirectory(\n  config: BrandKitConfig,\n  onUpdate: (index: DesignSystemIndex) => void,\n): () => Promise<void> {\n  let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n  const DEBOUNCE_MS = 300;\n\n  const watcher = chokidar.watch(config.brand.root, {\n    persistent: true,\n    ignoreInitial: true,\n    ignored: [\n      /(^|[/\\\\])\\./,  // Ignore dotfiles\n      '**/node_modules/**',\n    ],\n    awaitWriteFinish: {\n      stabilityThreshold: 200,\n      pollInterval: 50,\n    },\n  });\n\n  const runReindex = createReindexRunner(async () => {\n    console.error('[hot-reload] File change detected, re-indexing...');\n    const startTime = Date.now();\n    const newIndex = await buildDesignSystemIndex(config);\n    console.error(`[hot-reload] Re-indexed in ${Date.now() - startTime}ms`);\n    return newIndex;\n  }, onUpdate);\n\n  const triggerReindex = () => {\n    if (debounceTimer) clearTimeout(debounceTimer);\n    debounceTimer = setTimeout(() => {\n      void runReindex();\n    }, DEBOUNCE_MS);\n  };\n\n  watcher.on('add', triggerReindex);\n  watcher.on('change', triggerReindex);\n  watcher.on('unlink', triggerReindex);\n\n  return async () => {\n    if (debounceTimer) clearTimeout(debounceTimer);\n    try {\n      await watcher.close();\n    } catch (err) {\n      console.error('[hot-reload] Failed to close watcher:', err);\n    }\n  };\n}\n","/**\n * @file preview/server.ts\n * @description Local preview server for browsing the brand atomic system\n * visually. Renders the v2 index: colors, typography, token specimens,\n * components, assets, fonts, motion, the verbal layer, raw CSS, and search.\n */\n\nimport express from 'express';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { existsSync, readFileSync } from 'fs';\nimport ejs from 'ejs';\nimport type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandKitConfig } from '../types/config.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { handler as searchBrandHandler } from '../tools/search-brand.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/** Mutable reference wrapper so hot-reload can update the live index. */\nexport interface IndexRef {\n  current: DesignSystemIndex;\n}\n\nconst CONTEXTS = ['base', 'web', 'product'] as const;\n\n/** Coerce a ?context= query value to a valid BrandContext (default base). */\nfunction pickContext(value: unknown): BrandContext {\n  return typeof value === 'string' && (CONTEXTS as readonly string[]).includes(value)\n    ? (value as BrandContext)\n    : 'base';\n}\n\n/**\n * Resolve the preview asset directories. Works in both development\n * (src/preview/) and production (dist/preview/ or dist/cli/).\n */\nfunction resolvePreviewDirs(): { templatesDir: string; staticDir: string } {\n  // Candidate locations in priority order\n  const candidates = [\n    // When running from src/preview/ directly (dev / ts-node)\n    join(__dirname, 'templates'),\n    // When bundled into dist/cli/ and assets copied to dist/preview/\n    join(__dirname, '..', 'preview', 'templates'),\n    // When bundled into dist/ root and assets copied to dist/preview/\n    join(__dirname, 'preview', 'templates'),\n  ];\n\n  for (const candidate of candidates) {\n    if (existsSync(candidate)) {\n      const base = dirname(candidate);\n      return {\n        templatesDir: candidate,\n        staticDir: join(base, 'static'),\n      };\n    }\n  }\n\n  // Fallback -- use __dirname-relative (original behavior)\n  return {\n    templatesDir: join(__dirname, 'templates'),\n    staticDir: join(__dirname, 'static'),\n  };\n}\n\n/**\n * Creates the Express preview server application.\n * Accepts either a plain DesignSystemIndex or an IndexRef so that hot-reload\n * can swap the underlying index without restarting the server.\n * @param indexOrRef - The design system index or a mutable ref to one\n * @param config - BrandKit configuration\n * @returns Express application\n */\nexport function createPreviewServer(\n  indexOrRef: DesignSystemIndex | IndexRef,\n  config: BrandKitConfig,\n): express.Application {\n  const app = express();\n\n  // Normalise to a ref object so route handlers always read the latest index\n  const ref: IndexRef = 'current' in indexOrRef\n    ? indexOrRef as IndexRef\n    : { current: indexOrRef };\n\n  const { templatesDir, staticDir } = resolvePreviewDirs();\n\n  // Serve static files\n  app.use('/static', express.static(staticDir));\n\n  // Template rendering helper\n  function renderPage(template: string, data: Record<string, unknown>): string {\n    const index = ref.current;\n    const templatePath = join(templatesDir, `${template}.ejs`);\n    const layoutPath = join(templatesDir, 'layout.ejs');\n\n    let templateContent: string;\n    try {\n      templateContent = readFileSync(templatePath, 'utf-8');\n    } catch {\n      templateContent = '<h1>Template not found</h1>';\n    }\n\n    let body: string;\n    try {\n      body = ejs.render(templateContent, { ...data, config, index });\n    } catch (err) {\n      // Tolerance principle: a broken template renders an error page, not a 500.\n      body = `<h1>Template error</h1><pre>${String(err)}</pre>`;\n    }\n\n    let layoutContent: string;\n    try {\n      layoutContent = readFileSync(layoutPath, 'utf-8');\n    } catch {\n      return body;\n    }\n\n    try {\n      return ejs.render(layoutContent, { body, title: data.title ?? config.brand.name, config });\n    } catch {\n      return body;\n    }\n  }\n\n  // Routes\n  app.get('/', (_req, res) => {\n    res.send(renderPage('index', { title: `${config.brand.name} Brand System` }));\n  });\n\n  app.get('/colors', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    res.send(renderPage('colors', {\n      title: 'Colors',\n      ctx,\n      colors: ref.current.resolved[ctx].colors,\n    }));\n  });\n\n  app.get('/typography', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    res.send(renderPage('typography', {\n      title: 'Typography',\n      ctx,\n      typography: ref.current.resolved[ctx].typography,\n    }));\n  });\n\n  app.get('/tokens', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    res.send(renderPage('tokens', {\n      title: 'Design Tokens',\n      ctx,\n      tokens: ref.current.resolved[ctx].tokens,\n    }));\n  });\n\n  app.get('/components', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    res.send(renderPage('components', {\n      title: 'Components',\n      ctx,\n      components: ref.current.resolved[ctx].components,\n    }));\n  });\n\n  app.get('/assets', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    const index = ref.current;\n    // Override layer falls through to base when empty (same rule as get_assets).\n    const assets = index[ctx].assets.length ? index[ctx].assets : index.base.assets;\n    res.send(renderPage('assets', { title: 'Assets', ctx, assets }));\n  });\n\n  app.get('/fonts', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    const index = ref.current;\n    const fonts = index[ctx].fonts.length ? index[ctx].fonts : index.base.fonts;\n    res.send(renderPage('fonts', { title: 'Fonts', ctx, fonts }));\n  });\n\n  app.get('/motion', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    const index = ref.current;\n    res.send(renderPage('motion', {\n      title: 'Motion',\n      ctx,\n      motion: index[ctx].motion ?? index.base.motion,\n    }));\n  });\n\n  app.get('/verbal', (_req, res) => {\n    res.send(renderPage('verbal', { title: 'Verbal Identity' }));\n  });\n\n  app.get('/css', (req, res) => {\n    const ctx = pickContext(req.query.context);\n    const index = ref.current;\n    res.send(renderPage('css', {\n      title: 'CSS',\n      ctx,\n      colorsAndTypeCss:\n        index[ctx].colorsAndType?.rawContent ?? index.base.colorsAndType?.rawContent ?? '',\n      motionCss: index[ctx].motion?.css ?? index.base.motion?.css ?? '',\n    }));\n  });\n\n  app.get('/search', (req, res) => {\n    const query = typeof req.query.q === 'string' ? req.query.q : '';\n    interface SearchHit { kind: string; snippet: string; source?: string; context?: string }\n    let results: SearchHit[] = [];\n    if (query) {\n      try {\n        // Reuse the search_brand tool's tested search logic.\n        const [content] = searchBrandHandler(ref.current, { query });\n        results = (JSON.parse(content.text) as { results: SearchHit[] }).results;\n      } catch {\n        // Tolerance principle: render an empty result list, not a 500.\n      }\n    }\n    res.send(renderPage('search', { title: 'Search', query, results }));\n  });\n\n  return app;\n}\n","/**\n * @file search-brand.ts\n * @description MCP tool: search_brand\n * Full-text search across all brand atomic system content.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\n\nexport const TOOL_NAME = 'search_brand';\n\nexport const TOOL_DESCRIPTION =\n  'Full-text search across all brand atomic system content: verbal docs, magic_trick, components, tokens, assets, and CSS files.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    query: { type: 'string', description: 'Search query (case-insensitive substring)' },\n    limit: { type: 'number', default: 20 },\n  },\n  required: ['query'],\n};\n\ninterface SearchHit {\n  source?: string;\n  snippet: string;\n  score: number;\n  kind: 'verbal' | 'magic_trick' | 'component' | 'token' | 'asset' | 'css';\n  context?: string;\n}\n\nexport function handler(\n  index: DesignSystemIndex,\n  args: { query?: unknown; limit?: number },\n) {\n  if (typeof args.query !== 'string' || args.query.length === 0) {\n    return [\n      {\n        type: 'text' as const,\n        text: JSON.stringify(\n          { query: null, results: [], _warnings: ['Missing or invalid required \"query\" argument'] },\n          null,\n          2,\n        ),\n      },\n    ];\n  }\n  const q = args.query.toLowerCase();\n  const limit = args.limit ?? 20;\n  const warnings: string[] = [];\n  const hits: SearchHit[] = [];\n\n  function maybeHit(text: string | undefined, base: Omit<SearchHit, 'snippet' | 'score'>) {\n    if (!text) return;\n    const lc = text.toLowerCase();\n    const idx = lc.indexOf(q);\n    if (idx === -1) return;\n    const start = Math.max(0, idx - 40);\n    const end = Math.min(text.length, idx + q.length + 40);\n    hits.push({\n      ...base,\n      snippet: (start > 0 ? '…' : '') + text.slice(start, end) + (end < text.length ? '…' : ''),\n      score: 1 - idx / Math.max(1, text.length),\n    });\n  }\n\n  // Verbal docs\n  maybeHit(index.verbal.positioning?.body, { kind: 'verbal', source: index.verbal.positioning?.source });\n  maybeHit(index.verbal.messaging?.body, { kind: 'verbal', source: index.verbal.messaging?.source });\n  maybeHit(index.verbal.differentiation?.body, { kind: 'verbal', source: index.verbal.differentiation?.source });\n  maybeHit(index.verbal.concepts?.body, { kind: 'verbal', source: index.verbal.concepts?.source });\n  maybeHit(index.verbal.voice?.body, { kind: 'verbal', source: index.verbal.voice?.source });\n  if (index.verbal.audience) {\n    maybeHit(JSON.stringify(index.verbal.audience.data), { kind: 'verbal', source: index.verbal.audience.source });\n  }\n  maybeHit(index.magicTrick?.content, { kind: 'magic_trick', source: index.magicTrick?.source });\n\n  for (const ctx of ['base', 'web', 'product'] as const) {\n    const bucket = index[ctx];\n    for (const c of bucket.components) {\n      const blob = `${c.name} ${c.category ?? ''} ${c.description ?? ''} ${c.usage ?? ''} ${(c.examples ?? []).join(' ')}`;\n      maybeHit(blob, { kind: 'component', source: c.source, context: ctx });\n    }\n    for (const t of bucket.tokens) {\n      const blob = `${t.name} ${t.value} ${t.role ?? ''} ${t.body}`;\n      maybeHit(blob, { kind: 'token', source: t.source, context: ctx });\n    }\n    for (const a of bucket.assets) {\n      const blob = `${a.id ?? ''} ${a.file} ${a.purpose ?? ''}`;\n      maybeHit(blob, { kind: 'asset', source: a.filePath, context: ctx });\n    }\n    if (bucket.colorsAndType?.rawContent) {\n      maybeHit(bucket.colorsAndType.rawContent, { kind: 'css', source: bucket.colorsAndType.filePath, context: ctx });\n    }\n  }\n\n  hits.sort((a, b) => b.score - a.score);\n  const results = hits.slice(0, limit);\n\n  if (results.length === 0) warnings.push(`No matches for \"${args.query}\"`);\n\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify({ query: args.query, results, _warnings: warnings }, null, 2),\n    },\n  ];\n}\n","/**\n * @file index.ts\n * @description Main entry point for the BrandKit MCP server.\n *\n * Creates and starts the MCP server with stdio, SSE, or Streamable HTTP\n * transport. Loads the brand configuration, builds the design system index,\n * registers all MCP tools / resources / prompts, and optionally starts a\n * file watcher for hot-reload during development.\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { loadConfigWithPath, resolveConfigPaths } from './config/loader.js';\nimport { buildDesignSystemIndex } from './indexer/index.js';\nimport { registerAllTools } from './tools/index.js';\nimport { watchBrandDirectory } from './indexer/hot-reload.js';\nimport type { DesignSystemIndex } from './indexer/types.js';\nimport { dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { getPackageVersion } from './version.js';\n\n/** Current design system index -- updated on hot-reload. */\nlet currentIndex: DesignSystemIndex;\n\nexport type Transport = 'stdio' | 'sse' | 'http';\n\nexport interface StartServerOptions {\n  transport?: Transport;\n  port?: number;\n  configPath?: string;\n  watch?: boolean;\n}\n\n/**\n * Starts the BrandKit MCP server.\n */\nexport async function startServer(options: StartServerOptions = {}): Promise<void> {\n  const transport = options.transport ?? 'stdio';\n\n  // Log to stderr (stdout is reserved for MCP protocol in stdio mode)\n  console.error('[brandkit-mcp] Starting server...');\n\n  const { config: rawConfig, filePath } = loadConfigWithPath(options.configPath);\n  // Always resolve relative paths in the config against the config file's\n  // own directory. This makes the server portable across cwd values --\n  // e.g. when spawned by mcp-proxy, Claude Desktop, or via Glama, which\n  // may set the working directory to something other than the install dir.\n  const configDir = dirname(filePath);\n  const config = resolveConfigPaths(rawConfig, configDir);\n  console.error(`[brandkit-mcp] Loaded config for \"${config.brand.name}\" from ${filePath}`);\n\n  console.error('[brandkit-mcp] Building design system index...');\n  const startTime = Date.now();\n  currentIndex = await buildDesignSystemIndex(config);\n  const elapsed = Date.now() - startTime;\n  console.error(`[brandkit-mcp] Indexed ${currentIndex.base.tokens.length + currentIndex.base.components.length + currentIndex.base.assets.length} assets in ${elapsed}ms`);\n\n  const server = new Server(\n    { name: 'brandkit-mcp', version: getPackageVersion() },\n    { capabilities: { tools: {}, resources: {}, prompts: {} } },\n  );\n\n  registerAllTools(server, () => currentIndex);\n\n  if (options.watch) {\n    console.error('[brandkit-mcp] File watching enabled');\n    const stopWatcher = watchBrandDirectory(config, (newIndex) => {\n      currentIndex = newIndex;\n      console.error(`[brandkit-mcp] Index updated: ${newIndex.base.tokens.length + newIndex.base.components.length + newIndex.base.assets.length} assets`);\n    });\n    // Close the watcher on shutdown so the process can exit cleanly.\n    const shutdown = (signal: NodeJS.Signals) => {\n      void stopWatcher().finally(() => process.exit(signal === 'SIGINT' ? 130 : 143));\n    };\n    process.once('SIGINT', shutdown);\n    process.once('SIGTERM', shutdown);\n  }\n\n  if (transport === 'stdio') {\n    const stdioTransport = new StdioServerTransport();\n    await server.connect(stdioTransport);\n    console.error('[brandkit-mcp] Server running on stdio');\n    return;\n  }\n\n  // HTTP-based transports\n  const express = (await import('express')).default;\n  const app = express();\n  const port = options.port ?? config.server.port ?? 3001;\n\n  if (transport === 'sse') {\n    const { SSEServerTransport } = await import('@modelcontextprotocol/sdk/server/sse.js');\n    // Map per-session-id -> transport so multiple clients can connect.\n    const sessions = new Map<string, InstanceType<typeof SSEServerTransport>>();\n\n    app.get('/sse', async (_req, res) => {\n      try {\n        // The MCP SDK allows one transport per Server instance, so each SSE\n        // connection gets its own Server sharing the index via closure.\n        const sessionServer = new Server(\n          { name: 'brandkit-mcp', version: getPackageVersion() },\n          { capabilities: { tools: {}, resources: {}, prompts: {} } },\n        );\n        registerAllTools(sessionServer, () => currentIndex);\n        const t = new SSEServerTransport('/messages', res);\n        sessions.set(t.sessionId, t);\n        res.on('close', () => sessions.delete(t.sessionId));\n        await sessionServer.connect(t);\n      } catch (err) {\n        console.error('[brandkit-mcp] Request handler error:', err);\n        if (!res.headersSent) {\n          res.status(500).json({ error: 'Internal server error' });\n        }\n      }\n    });\n\n    app.post('/messages', async (req, res) => {\n      try {\n        const sessionId = (req.query.sessionId as string) ?? '';\n        const t = sessions.get(sessionId);\n        if (!t) {\n          res.status(400).json({ error: 'No active SSE session for sessionId' });\n          return;\n        }\n        await t.handlePostMessage(req, res);\n      } catch (err) {\n        console.error('[brandkit-mcp] Request handler error:', err);\n        if (!res.headersSent) {\n          res.status(500).json({ error: 'Internal server error' });\n        }\n      }\n    });\n\n    app.listen(port, () => {\n      console.error(`[brandkit-mcp] SSE server running at http://localhost:${port}`);\n      console.error(`[brandkit-mcp] Connect via SSE at http://localhost:${port}/sse`);\n    });\n    return;\n  }\n\n  if (transport === 'http') {\n    // Streamable HTTP transport (MCP spec 2025-03-26)\n    const { StreamableHTTPServerTransport } = await import('@modelcontextprotocol/sdk/server/streamableHttp.js');\n    app.use(express.json());\n\n    const httpTransport = new StreamableHTTPServerTransport({\n      sessionIdGenerator: undefined, // stateless: simpler for single-tenant brand servers\n    });\n    await server.connect(httpTransport);\n\n    app.all('/mcp', async (req, res) => {\n      await httpTransport.handleRequest(req, res, req.body);\n    });\n\n    app.listen(port, () => {\n      console.error(`[brandkit-mcp] Streamable HTTP server running at http://localhost:${port}/mcp`);\n    });\n    return;\n  }\n\n  throw new Error(`Unknown transport: ${transport}`);\n}\n\n// Auto-start when this file is the direct entry point (e.g. `node dist/index.js`).\nconst isDirectRun = (() => {\n  try {\n    return process.argv[1] === fileURLToPath(import.meta.url);\n  } catch {\n    return false;\n  }\n})();\nif (isDirectRun) {\n  startServer().catch((err) => {\n    console.error('[brandkit-mcp] Fatal error:', err);\n    process.exit(1);\n  });\n}\n","/**\n * @file tools/index.ts\n * @description Registers all MCP primitives (tools, resources, prompts)\n * on the server instance. Imports the request schemas synchronously so\n * handlers are wired up before the transport connects.\n */\n\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n  ListToolsRequestSchema,\n  CallToolRequestSchema,\n  ListResourcesRequestSchema,\n  ReadResourceRequestSchema,\n  ListPromptsRequestSchema,\n  GetPromptRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { DesignSystemIndex } from '../indexer/types.js';\n\nimport * as brandOverview    from './get-brand-overview.js';\nimport * as magicTrick       from './get-magic-trick.js';\nimport * as positioning      from './get-positioning.js';\nimport * as audience         from './get-audience.js';\nimport * as messaging        from './get-messaging.js';\nimport * as differentiation  from './get-differentiation.js';\nimport * as concepts         from './get-concepts.js';\nimport * as voice            from './get-voice.js';\nimport * as colorsAndType    from './get-colors-and-type.js';\nimport * as assets           from './get-assets.js';\nimport * as fonts            from './get-fonts.js';\nimport * as components       from './get-components.js';\nimport * as tokens           from './get-tokens.js';\nimport * as motion           from './get-motion.js';\nimport * as css              from './get-css.js';\nimport * as searchBrand      from './search-brand.js';\nimport * as validateUsage    from './validate-usage.js';\nimport * as contextDiff      from './get-context-diff.js';\n\nimport { listResources, readResource } from '../resources/index.js';\nimport { listPrompts, getPrompt } from '../prompts/index.js';\n\n/** All tool modules in registration order (v2 surface, 18 tools). */\nconst ALL_TOOLS = [\n  brandOverview,\n  magicTrick,\n  positioning,\n  audience,\n  messaging,\n  differentiation,\n  concepts,\n  voice,\n  colorsAndType,\n  assets,\n  fonts,\n  components,\n  tokens,\n  motion,\n  css,\n  searchBrand,\n  validateUsage,\n  contextDiff,\n] as const;\n\n/**\n * Registers all design system tools, resources, and prompts on the MCP server.\n *\n * @param server - MCP Server instance\n * @param getIndex - Function that returns the current design system index\n *                   (supports hot-reload by always fetching the latest)\n */\nexport function registerAllTools(\n  server: Server,\n  getIndex: () => DesignSystemIndex,\n): void {\n  // ---- Tools --------------------------------------------------------------\n\n  server.setRequestHandler(ListToolsRequestSchema, async () => ({\n    tools: ALL_TOOLS.map((t) => ({\n      name: t.TOOL_NAME,\n      description: t.TOOL_DESCRIPTION,\n      inputSchema: t.INPUT_SCHEMA,\n    })),\n  }));\n\n  server.setRequestHandler(CallToolRequestSchema, async (request) => {\n    const { name, arguments: args = {} } = request.params;\n    const index = getIndex();\n\n    try {\n      switch (name) {\n        case brandOverview.TOOL_NAME:    return { content: brandOverview.handler(index) };\n        case magicTrick.TOOL_NAME:       return { content: magicTrick.handler(index) };\n        case positioning.TOOL_NAME:      return { content: positioning.handler(index) };\n        case audience.TOOL_NAME:         return { content: audience.handler(index) };\n        case messaging.TOOL_NAME:        return { content: messaging.handler(index) };\n        case differentiation.TOOL_NAME:  return { content: differentiation.handler(index) };\n        case concepts.TOOL_NAME:         return { content: concepts.handler(index) };\n        case voice.TOOL_NAME:            return { content: voice.handler(index) };\n        case colorsAndType.TOOL_NAME:    return { content: colorsAndType.handler(index, args as never) };\n        case assets.TOOL_NAME:           return { content: assets.handler(index, args as never) };\n        case fonts.TOOL_NAME:            return { content: fonts.handler(index, args as never) };\n        case components.TOOL_NAME:       return { content: components.handler(index, args as never) };\n        case tokens.TOOL_NAME:           return { content: tokens.handler(index, args as never) };\n        case motion.TOOL_NAME:           return { content: motion.handler(index, args as never) };\n        case css.TOOL_NAME:              return { content: css.handler(index, args as never) };\n        case searchBrand.TOOL_NAME:      return { content: searchBrand.handler(index, args as never) };\n        case validateUsage.TOOL_NAME:    return { content: validateUsage.handler(index, args as never) };\n        case contextDiff.TOOL_NAME:      return { content: contextDiff.handler(index, args as never) };\n        default:\n          return {\n            content: [{ type: 'text' as const, text: `Unknown tool: ${name}` }],\n            isError: true,\n          };\n      }\n    } catch (err) {\n      const message = err instanceof Error ? err.message : String(err);\n      return {\n        content: [{ type: 'text' as const, text: `Error executing ${name}: ${message}` }],\n        isError: true,\n      };\n    }\n  });\n\n  // ---- Resources ----------------------------------------------------------\n\n  server.setRequestHandler(ListResourcesRequestSchema, async () => ({\n    resources: listResources(getIndex()),\n  }));\n\n  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n    return readResource(request.params.uri, getIndex());\n  });\n\n  // ---- Prompts ------------------------------------------------------------\n\n  server.setRequestHandler(ListPromptsRequestSchema, async () => ({\n    prompts: listPrompts(),\n  }));\n\n  server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n    return getPrompt(request.params.name, request.params.arguments ?? {}, getIndex());\n  });\n}\n","/**\n * @file get-brand-overview.ts\n * @description MCP tool: get_brand_overview\n * Returns a high-level overview of the design system including brand name,\n * contexts, asset inventory, available 18 tools, and taste primer.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_brand_overview';\n\nexport const TOOL_DESCRIPTION =\n  'High-level overview of the brand atomic system: brand name, magic_trick presence, inventory counts, contexts, and the full v2 tool list.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nconst TOOLS: ReadonlyArray<readonly [string, string]> = [\n  ['get_brand_overview', 'High-level overview + taste primer'],\n  ['get_magic_trick', 'Verbatim magic_trick.md'],\n  ['get_positioning', 'Positioning document'],\n  ['get_audience', 'Audience YAML, parsed'],\n  ['get_messaging', 'Messaging document'],\n  ['get_differentiation', 'Differentiation document'],\n  ['get_concepts', 'Creative concepts/directions'],\n  ['get_voice', 'Voice document'],\n  ['get_colors_and_type', 'Colors + typography custom properties'],\n  ['get_assets', 'Logos + brand assets (replaces v1 get_logos + get_textures)'],\n  ['get_fonts', 'Font faces from fonts/'],\n  ['get_components', 'UI primitives'],\n  ['get_tokens', 'Token specimens'],\n  ['get_motion', 'Motion system (json + css)'],\n  ['get_css', 'colors_and_type.css + motion.css text'],\n  ['search_brand', 'Full-text search'],\n  ['validate_usage', 'Validate brand compliance'],\n  ['get_context_diff', 'Diff base vs web vs product'],\n];\n\n/**\n * Handles the get_brand_overview tool call.\n * @param index - The design system index\n * @returns MCP CallToolResult content\n */\nexport function handler(index: DesignSystemIndex) {\n  const payload = {\n    name: index.brandName,\n    description: index.brandDescription,\n    lastIndexed: index.lastIndexed.toISOString(),\n    contexts: ['base', 'web', 'product'] as const,\n    inventory: {\n      tokens: index.base.tokens.length,\n      components: index.base.components.length,\n      fonts: index.base.fonts.length,\n      assets: index.base.assets.length,\n      motion: index.base.motion != null,\n      verbal: {\n        positioning: index.verbal.positioning != null,\n        audience: index.verbal.audience != null,\n        messaging: index.verbal.messaging != null,\n        differentiation: index.verbal.differentiation != null,\n        concepts: index.verbal.concepts != null,\n        voice: index.verbal.voice != null,\n      },\n      magicTrick: index.magicTrick != null,\n    },\n    availableTools: TOOLS.map(([name, description]) => ({ name, description })),\n    _warnings: index.warnings,\n  };\n\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(attachTastePrimer(payload, index), null, 2),\n    },\n  ];\n}\n\n","import type { DesignSystemIndex } from '../indexer/types.js';\n\nexport function attachTastePrimer<T extends object>(\n  payload: T,\n  index: DesignSystemIndex,\n): T & { _taste_primer: string | null } {\n  return {\n    ...payload,\n    _taste_primer: index.magicTrick?.content ?? null,\n  };\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\n\nexport const TOOL_NAME = 'get_magic_trick';\n\nexport const TOOL_DESCRIPTION =\n  'Return the human-authored magic_trick.md taste primer verbatim. This file is human-write-only — never write to it via any tool.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const warnings: string[] = [];\n  const mt = index.magicTrick;\n  if (!mt) warnings.push('No magic_trick.md found at brand root.');\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        {\n          content: mt?.content ?? '',\n          source: mt?.source,\n          _warnings: warnings,\n        },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_positioning';\n\nexport const TOOL_DESCRIPTION =\n  \"Return the brand's positioning document (agent/verbal/positioning.md). Includes a taste primer from magic_trick.md.\";\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const doc = index.verbal.positioning;\n  const warnings: string[] = [];\n\n  if (!doc) {\n    warnings.push('No positioning document found at agent/verbal/positioning.md');\n  }\n\n  const payload = attachTastePrimer(\n    {\n      content: doc?.body ?? '',\n      frontmatter: doc?.frontmatter ?? {},\n      source: doc?.source,\n      _warnings: warnings,\n    },\n    index,\n  );\n\n  return [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_audience';\n\nexport const TOOL_DESCRIPTION =\n  \"Return the brand's audience definition parsed from agent/verbal/audience.yaml. Freeform YAML; returned as-is. Includes a taste primer.\";\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const warnings: string[] = [];\n  const doc = index.verbal.audience;\n  if (!doc) warnings.push('No audience document found at agent/verbal/audience.yaml');\n\n  const payload = attachTastePrimer(\n    {\n      data: doc?.data ?? null,\n      source: doc?.source,\n      _warnings: warnings,\n    },\n    index,\n  );\n  return [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_messaging';\n\nexport const TOOL_DESCRIPTION =\n  \"Return the brand's messaging document (agent/verbal/messaging.md). Includes a taste primer.\";\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const doc = index.verbal.messaging;\n  const warnings: string[] = [];\n\n  if (!doc) {\n    warnings.push('No messaging document found at agent/verbal/messaging.md');\n  }\n\n  const payload = attachTastePrimer(\n    {\n      content: doc?.body ?? '',\n      frontmatter: doc?.frontmatter ?? {},\n      source: doc?.source,\n      _warnings: warnings,\n    },\n    index,\n  );\n\n  return [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_differentiation';\n\nexport const TOOL_DESCRIPTION =\n  \"Return the brand's differentiation document (agent/verbal/differentiation.md). Includes a taste primer.\";\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const doc = index.verbal.differentiation;\n  const warnings: string[] = [];\n\n  if (!doc) {\n    warnings.push('No differentiation document found at agent/verbal/differentiation.md');\n  }\n\n  const payload = attachTastePrimer(\n    {\n      content: doc?.body ?? '',\n      frontmatter: doc?.frontmatter ?? {},\n      source: doc?.source,\n      _warnings: warnings,\n    },\n    index,\n  );\n\n  return [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_concepts';\n\nexport const TOOL_DESCRIPTION =\n  \"Return the brand's creative concepts/directions (agent/verbal/concepts.md). Includes a taste primer.\";\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const doc = index.verbal.concepts;\n  const warnings: string[] = [];\n\n  if (!doc) {\n    warnings.push('No concepts document found at agent/verbal/concepts.md');\n  }\n\n  const payload = attachTastePrimer(\n    {\n      content: doc?.body ?? '',\n      frontmatter: doc?.frontmatter ?? {},\n      source: doc?.source,\n      _warnings: warnings,\n    },\n    index,\n  );\n\n  return [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport { attachTastePrimer } from './_taste-primer.js';\n\nexport const TOOL_NAME = 'get_voice';\n\nexport const TOOL_DESCRIPTION =\n  \"Return the brand's voice document (agent/verbal/voice.md). Includes a taste primer.\";\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {},\n};\n\nexport function handler(index: DesignSystemIndex) {\n  const doc = index.verbal.voice;\n  const warnings: string[] = [];\n\n  if (!doc) {\n    warnings.push('No voice document found at agent/verbal/voice.md');\n  }\n\n  const payload = attachTastePrimer(\n    {\n      content: doc?.body ?? '',\n      frontmatter: doc?.frontmatter ?? {},\n      source: doc?.source,\n      _warnings: warnings,\n    },\n    index,\n  );\n\n  return [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_colors_and_type';\n\nexport const TOOL_DESCRIPTION =\n  'Return colors and typography as CSS custom properties from agent/visual/colors_and_type.css (with optional artifact override).';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n  },\n};\n\nexport function handler(index: DesignSystemIndex, args: { context?: BrandContext }) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n  const file = index[ctx].colorsAndType ?? index.base.colorsAndType;\n  if (!file) warnings.push('No colors_and_type.css found');\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        {\n          context: ctx,\n          customProperties: file?.customProperties ?? {},\n          source: file?.filePath,\n          _warnings: warnings,\n        },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n","/**\n * @file _context.ts\n * @description Runtime coercion for the `context` tool argument.\n * The MCP SDK does not enforce inputSchema enums at runtime, so tools must\n * tolerate out-of-enum values per the tolerance principle: fall back to\n * 'base' and record a warning instead of throwing.\n */\n\nimport type { BrandContext } from '../types/design-system.js';\n\nconst CONTEXTS = ['base', 'web', 'product'] as const;\n\nexport function coerceContext(value: unknown, warnings: string[]): BrandContext {\n  if (value === undefined || value === null) return 'base';\n  if (typeof value === 'string' && (CONTEXTS as readonly string[]).includes(value)) {\n    return value as BrandContext;\n  }\n  warnings.push(`Unknown context \"${String(value)}\"; falling back to \"base\"`);\n  return 'base';\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_assets';\n\nexport const TOOL_DESCRIPTION =\n  'Return logos and other binary assets from agent/visual/assets/. Replaces v1 get_logos + get_textures.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n  },\n};\n\nexport function handler(index: DesignSystemIndex, args: { context?: BrandContext }) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n  const list = index[ctx].assets.length ? index[ctx].assets : index.base.assets;\n  if (list.length === 0) warnings.push('No assets found');\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify({ context: ctx, assets: list, _warnings: warnings }, null, 2),\n    },\n  ];\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_fonts';\n\nexport const TOOL_DESCRIPTION =\n  'Return font faces declared in agent/visual/fonts/ (binary files + optional fonts.yaml manifest).';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n  },\n};\n\nexport function handler(index: DesignSystemIndex, args: { context?: BrandContext }) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n  const faces = index[ctx].fonts.length ? index[ctx].fonts : index.base.fonts;\n  if (faces.length === 0) warnings.push('No font faces discovered');\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify({ context: ctx, faces, _warnings: warnings }, null, 2),\n    },\n  ];\n}\n","/**\n * @file get-components.ts\n * @description MCP tool: get_components\n * Returns component specifications from agent/visual/components/.\n * Supports filtering by context (base | web | product) and name.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_components';\n\nexport const TOOL_DESCRIPTION =\n  'Return UI component specifications from agent/visual/components/. Optionally filtered by context (base | web | product).';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n    name: { type: 'string', description: 'Filter to a single component by name' },\n  },\n};\n\n/**\n * Handles the get_components tool call.\n */\nexport function handler(\n  index: DesignSystemIndex,\n  args: { context?: BrandContext; name?: string },\n) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n\n  // Use override layer if it has components; otherwise fall through to base.\n  const list = index[ctx].components.length ? index[ctx].components : index.base.components;\n\n  let filtered = list;\n  if (typeof args.name === 'string' && args.name.length > 0) {\n    const name = args.name;\n    filtered = filtered.filter((c) => c.name.toLowerCase() === name.toLowerCase());\n    if (filtered.length === 0) warnings.push(`No component named \"${name}\" in ${ctx} context`);\n  } else if (filtered.length === 0) {\n    warnings.push('No components found');\n  }\n\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        { context: ctx, components: filtered, _warnings: warnings },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n\n","/**\n * @file get-tokens.ts\n * @description MCP tool: get_tokens\n * Returns design tokens from agent/visual/tokens/ specimens.\n * Supports output formats: json, css, scss, tailwind, w3c.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\nimport { toCSS, toSCSS, toTailwind, toW3C } from '../formatters/token-formatters.js';\n\nexport const TOOL_NAME = 'get_tokens';\n\nexport const TOOL_DESCRIPTION =\n  'Return design tokens from agent/visual/tokens/ specimens. Optional context (base|web|product) and output format (json|css|scss|tailwind|w3c).';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n    format: {\n      type: 'string',\n      enum: ['json', 'css', 'scss', 'tailwind', 'w3c'],\n      default: 'json',\n    },\n    type: { type: 'string', description: 'Filter by token type (color, font, radius, spacing, etc.)' },\n  },\n};\n\n/**\n * Handles the get_tokens tool call.\n */\nexport function handler(\n  index: DesignSystemIndex,\n  args: {\n    context?: BrandContext;\n    format?: 'json' | 'css' | 'scss' | 'tailwind' | 'w3c';\n    type?: string;\n  },\n) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n  const format = args.format ?? 'json';\n\n  let tokens = index[ctx].tokens.length ? index[ctx].tokens : index.base.tokens;\n  if (args.type) {\n    tokens = tokens.filter((t) => t.type === args.type);\n  }\n  if (tokens.length === 0) warnings.push('No token specimens found');\n\n  let text: string;\n  switch (format) {\n    case 'css':\n      text = toCSS(tokens);\n      break;\n    case 'scss':\n      text = toSCSS(tokens);\n      break;\n    case 'tailwind':\n      text = toTailwind(tokens);\n      break;\n    case 'w3c':\n      text = toW3C(tokens);\n      break;\n    default:\n      text = JSON.stringify({ context: ctx, tokens, _warnings: warnings }, null, 2);\n  }\n\n  // Surface warnings in a format-appropriate way: a comment for text formats,\n  // an embedded _warnings key for JSON-document formats (tailwind, w3c).\n  if (warnings.length > 0) {\n    if (format === 'css' || format === 'scss') {\n      text = `/* warnings: ${warnings.join('; ')} */\\n${text}`;\n    } else if (format === 'tailwind' || format === 'w3c') {\n      text = JSON.stringify(\n        { ...(JSON.parse(text) as Record<string, unknown>), _warnings: warnings },\n        null,\n        2,\n      );\n    }\n    // format === 'json' already embeds _warnings in its payload.\n  }\n\n  return [{ type: 'text' as const, text }];\n}\n\n","/**\n * @file token-formatters.ts\n * @description Output formatters for token specimens (css, scss, tailwind, w3c).\n * Consumed by the get_tokens tool.\n */\n\nimport type { TokenSpecimen } from '../types/design-system.js';\n\nexport function toCSS(tokens: TokenSpecimen[]): string {\n  const lines = tokens.map((t) => `  --${t.name}: ${t.value};`);\n  return `:root {\\n${lines.join('\\n')}\\n}\\n`;\n}\n\nexport function toSCSS(tokens: TokenSpecimen[]): string {\n  return tokens.map((t) => `$${t.name}: ${t.value};`).join('\\n') + '\\n';\n}\n\nexport function toTailwind(tokens: TokenSpecimen[]): string {\n  const byType: Record<string, Record<string, string>> = {};\n  for (const t of tokens) {\n    byType[t.type] ??= {};\n    byType[t.type][t.name] = t.value;\n  }\n  return JSON.stringify({ theme: { extend: byType } }, null, 2);\n}\n\nexport function toW3C(tokens: TokenSpecimen[]): string {\n  const out: Record<string, { $value: string; $type: string; $description?: string }> = {};\n  for (const t of tokens) {\n    out[t.name] = { $value: t.value, $type: t.type, $description: t.role };\n  }\n  return JSON.stringify(out, null, 2);\n}\n","import type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_motion';\n\nexport const TOOL_DESCRIPTION =\n  'Return the motion system: parsed motion.json tokens + motion.css text.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n  },\n};\n\nexport function handler(index: DesignSystemIndex, args: { context?: BrandContext }) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n  const motion = index[ctx].motion ?? index.base.motion;\n  if (!motion) warnings.push('No motion system found at agent/visual/motion/');\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        {\n          context: ctx,\n          tokens: motion?.tokens ?? null,\n          css: motion?.css ?? '',\n          source: motion?.source,\n          _warnings: warnings,\n        },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n","/**\n * @file get-css.ts\n * @description MCP tool: get_css\n * Returns raw CSS text from agent/visual/colors_and_type.css and\n * agent/visual/motion/motion.css for the requested context.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_css';\n\nexport const TOOL_DESCRIPTION =\n  'Return raw CSS text from agent/visual/colors_and_type.css and agent/visual/motion/motion.css for the requested context.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    context: { type: 'string', enum: ['base', 'web', 'product'], default: 'base' },\n  },\n};\n\n/**\n * Handles the get_css tool call.\n */\nexport function handler(\n  index: DesignSystemIndex,\n  args: { context?: BrandContext },\n) {\n  const warnings: string[] = [];\n  const ctx = coerceContext(args.context, warnings);\n\n  const colorsAndType =\n    index[ctx].colorsAndType?.rawContent ?? index.base.colorsAndType?.rawContent ?? '';\n  const motion = index[ctx].motion?.css ?? index.base.motion?.css ?? '';\n\n  if (!colorsAndType) warnings.push('No colors_and_type.css found');\n  if (!motion) warnings.push('No motion.css found');\n\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        { context: ctx, colors_and_type: colorsAndType, motion, _warnings: warnings },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n\n","/**\n * @file validate-usage.ts\n * @description MCP tool: validate_usage\n * Validates whether an HTML/CSS snippet uses brand tokens rather than literal\n * values, and references known components.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\n\nexport const TOOL_NAME = 'validate_usage';\n\nexport const TOOL_DESCRIPTION =\n  'Validate that an HTML/CSS snippet uses brand tokens (rather than literal values) and references known components.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    snippet: { type: 'string', description: 'HTML or CSS snippet to validate' },\n    format: { type: 'string', enum: ['html', 'css'], default: 'css' },\n  },\n  required: ['snippet'],\n};\n\ninterface Violation { rule: string; match: string; suggestion?: string }\n\nexport function handler(\n  index: DesignSystemIndex,\n  args: { snippet?: unknown; format?: 'html' | 'css' },\n) {\n  if (typeof args.snippet !== 'string') {\n    return [\n      {\n        type: 'text' as const,\n        text: JSON.stringify(\n          { violations: [], _warnings: ['Missing or invalid required \"snippet\" argument'] },\n          null,\n          2,\n        ),\n      },\n    ];\n  }\n\n  const warnings: string[] = [];\n  const violations: Violation[] = [];\n\n  // Collect canonical color values from v2 tokens\n  const colorTokens = index.base.tokens.filter((t) => t.type === 'color');\n  const knownColorValues = new Set(colorTokens.map((t) => t.value.toLowerCase()));\n\n  // Rule 1: flag literal hex colors that do not correspond to a known canonical token value.\n  // If the hex IS a canonical token value, skip the violation (the author used the right\n  // value but may not know the token name — not an error).\n  const hexRe = /#([0-9a-f]{3,8})\\b/gi;\n  for (const m of args.snippet.matchAll(hexRe)) {\n    const literal = `#${m[1]}`.toLowerCase();\n    if (knownColorValues.has(literal)) {\n      // Canonical value — not a violation.\n      continue;\n    }\n    violations.push({\n      rule: 'literal-color',\n      match: m[0],\n      suggestion: 'Replace with a brand token',\n    });\n  }\n\n  // Rule 2: HTML data-component values reference known components (HTML mode only)\n  if (args.format === 'html') {\n    const knownComponents = new Set(index.base.components.map((c) => c.name.toLowerCase()));\n    const dataRe = /data-component=[\"']([^\"']+)[\"']/g;\n    for (const m of args.snippet.matchAll(dataRe)) {\n      if (!knownComponents.has(m[1].toLowerCase())) {\n        violations.push({ rule: 'unknown-component', match: m[0], suggestion: `No component named \"${m[1]}\"` });\n      }\n    }\n  }\n\n  if (index.base.tokens.length === 0) warnings.push('No tokens indexed; color validation degraded.');\n\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        { violations, _warnings: warnings },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n","/**\n * @file get-context-diff.ts\n * @description MCP tool: get_context_diff\n * Diffs two contexts (base | web | product) across colors_and_type custom\n * properties, components, and tokens.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\nimport type { BrandContext } from '../types/design-system.js';\nimport { coerceContext } from './_context.js';\n\nexport const TOOL_NAME = 'get_context_diff';\n\nexport const TOOL_DESCRIPTION =\n  'Diff two contexts (base | web | product) across colors_and_type custom properties, components, and tokens.';\n\nexport const INPUT_SCHEMA = {\n  type: 'object' as const,\n  properties: {\n    a: { type: 'string', enum: ['base', 'web', 'product'], default: 'web' },\n    b: { type: 'string', enum: ['base', 'web', 'product'], default: 'product' },\n  },\n};\n\ninterface DiffEntry { name: string; a?: string; b?: string }\n\nexport function handler(\n  index: DesignSystemIndex,\n  args: { a?: BrandContext; b?: BrandContext },\n) {\n  const warnings: string[] = [];\n  const a = args.a == null ? 'web' : coerceContext(args.a, warnings);\n  const b = args.b == null ? 'product' : coerceContext(args.b, warnings);\n\n  // Custom properties (colors_and_type)\n  const propsA = index[a].colorsAndType?.customProperties ?? index.base.colorsAndType?.customProperties ?? {};\n  const propsB = index[b].colorsAndType?.customProperties ?? index.base.colorsAndType?.customProperties ?? {};\n  const allKeys = new Set([...Object.keys(propsA), ...Object.keys(propsB)]);\n  const changed: DiffEntry[] = [];\n  const onlyInA: DiffEntry[] = [];\n  const onlyInB: DiffEntry[] = [];\n  for (const k of allKeys) {\n    if (propsA[k] === undefined) onlyInB.push({ name: k, b: propsB[k] });\n    else if (propsB[k] === undefined) onlyInA.push({ name: k, a: propsA[k] });\n    else if (propsA[k] !== propsB[k]) changed.push({ name: k, a: propsA[k], b: propsB[k] });\n  }\n\n  // Components (override-aware: fall through to base if empty)\n  const compsA = (index[a].components.length ? index[a].components : index.base.components).map((c) => c.name);\n  const compsB = (index[b].components.length ? index[b].components : index.base.components).map((c) => c.name);\n  const compsAOnly = compsA.filter((n) => !compsB.includes(n));\n  const compsBOnly = compsB.filter((n) => !compsA.includes(n));\n\n  // Tokens\n  const tokensA = (index[a].tokens.length ? index[a].tokens : index.base.tokens).map((t) => t.name);\n  const tokensB = (index[b].tokens.length ? index[b].tokens : index.base.tokens).map((t) => t.name);\n  const tokensAOnly = tokensA.filter((n) => !tokensB.includes(n));\n  const tokensBOnly = tokensB.filter((n) => !tokensA.includes(n));\n\n  return [\n    {\n      type: 'text' as const,\n      text: JSON.stringify(\n        {\n          a,\n          b,\n          customProperties: { changed, onlyInA, onlyInB },\n          components: { onlyInA: compsAOnly, onlyInB: compsBOnly },\n          tokens: { onlyInA: tokensAOnly, onlyInB: tokensBOnly },\n          _warnings: warnings,\n        },\n        null,\n        2,\n      ),\n    },\n  ];\n}\n","/**\n * @file resources/index.ts\n * @description MCP Resources for BrandKit v2.\n *\n * Exposes design-system entities as addressable resources under the\n * `brand://` URI scheme so MCP clients can browse and read them\n * directly without invoking tools.\n *\n * URI patterns:\n *   brand://overview                    -- high-level overview + taste primer\n *   brand://magic_trick                 -- verbatim magic_trick.md\n *   brand://verbal/positioning          -- positioning document\n *   brand://verbal/audience             -- audience YAML\n *   brand://verbal/messaging            -- messaging document\n *   brand://verbal/differentiation      -- differentiation document\n *   brand://verbal/concepts             -- creative concepts\n *   brand://verbal/voice                -- voice document\n *   brand://visual/colors_and_type      -- colors + typography CSS\n *   brand://visual/components           -- UI primitives\n *   brand://visual/tokens               -- token specimens\n *   brand://visual/motion               -- motion system\n *   brand://visual/fonts                -- font faces\n *   brand://visual/assets               -- logos + binary assets\n */\n\nimport type { Resource } from '@modelcontextprotocol/sdk/types.js';\nimport type { DesignSystemIndex } from '../indexer/types.js';\n\nimport * as brandOverview    from '../tools/get-brand-overview.js';\nimport * as magicTrick       from '../tools/get-magic-trick.js';\nimport * as positioning      from '../tools/get-positioning.js';\nimport * as audience         from '../tools/get-audience.js';\nimport * as messaging        from '../tools/get-messaging.js';\nimport * as differentiation  from '../tools/get-differentiation.js';\nimport * as concepts         from '../tools/get-concepts.js';\nimport * as voice            from '../tools/get-voice.js';\nimport * as colorsAndType    from '../tools/get-colors-and-type.js';\nimport * as components       from '../tools/get-components.js';\nimport * as tokens           from '../tools/get-tokens.js';\nimport * as motion           from '../tools/get-motion.js';\nimport * as fonts            from '../tools/get-fonts.js';\nimport * as assets           from '../tools/get-assets.js';\n\n/** Canonical list of v2 brand:// resource URIs (14 total). */\nconst RESOURCE_DEFS: Array<{ uri: string; name: string; description: string }> = [\n  { uri: 'brand://overview',               name: 'Brand overview',  description: 'High-level overview + taste primer' },\n  { uri: 'brand://magic_trick',            name: 'Magic trick',     description: 'Human-authored taste primer' },\n  { uri: 'brand://verbal/positioning',     name: 'Positioning',     description: 'Verbal: positioning document' },\n  { uri: 'brand://verbal/audience',        name: 'Audience',        description: 'Verbal: audience YAML' },\n  { uri: 'brand://verbal/messaging',       name: 'Messaging',       description: 'Verbal: messaging document' },\n  { uri: 'brand://verbal/differentiation', name: 'Differentiation', description: 'Verbal: differentiation document' },\n  { uri: 'brand://verbal/concepts',        name: 'Concepts',        description: 'Verbal: creative concepts' },\n  { uri: 'brand://verbal/voice',           name: 'Voice',           description: 'Verbal: voice document' },\n  { uri: 'brand://visual/colors_and_type', name: 'Colors and Type', description: 'Visual: colors + typography CSS' },\n  { uri: 'brand://visual/components',      name: 'Components',      description: 'Visual: UI primitives' },\n  { uri: 'brand://visual/tokens',          name: 'Tokens',          description: 'Visual: token specimens' },\n  { uri: 'brand://visual/motion',          name: 'Motion',          description: 'Visual: motion system' },\n  { uri: 'brand://visual/fonts',           name: 'Fonts',           description: 'Visual: font faces' },\n  { uri: 'brand://visual/assets',          name: 'Assets',          description: 'Visual: logos + binary assets' },\n];\n\nexport function listResources(_index: DesignSystemIndex): Resource[] {\n  return RESOURCE_DEFS.map((r) => ({\n    uri: r.uri,\n    name: r.name,\n    description: r.description,\n    mimeType: 'application/json',\n  }));\n}\n\nexport async function readResource(uri: string, index: DesignSystemIndex): Promise<{\n  contents: Array<{ uri: string; mimeType?: string; text: string }>;\n}> {\n  const route = (handlerOutput: { type: 'text'; text: string }[]) => ({\n    contents: [{ uri, mimeType: 'application/json', text: handlerOutput[0].text }],\n  });\n\n  switch (uri) {\n    case 'brand://overview':               return route(brandOverview.handler(index));\n    case 'brand://magic_trick':            return route(magicTrick.handler(index));\n    case 'brand://verbal/positioning':     return route(positioning.handler(index));\n    case 'brand://verbal/audience':        return route(audience.handler(index));\n    case 'brand://verbal/messaging':       return route(messaging.handler(index));\n    case 'brand://verbal/differentiation': return route(differentiation.handler(index));\n    case 'brand://verbal/concepts':        return route(concepts.handler(index));\n    case 'brand://verbal/voice':           return route(voice.handler(index));\n    case 'brand://visual/colors_and_type': return route(colorsAndType.handler(index, { context: 'base' }));\n    case 'brand://visual/components':      return route(components.handler(index, { context: 'base' }));\n    case 'brand://visual/tokens':          return route(tokens.handler(index, { context: 'base' }));\n    case 'brand://visual/motion':          return route(motion.handler(index, { context: 'base' }));\n    case 'brand://visual/fonts':           return route(fonts.handler(index, { context: 'base' }));\n    case 'brand://visual/assets':          return route(assets.handler(index, { context: 'base' }));\n    default:\n      return { contents: [{ uri, mimeType: 'text/plain', text: `Unknown resource: ${uri}` }] };\n  }\n}\n","/**\n * @file prompts/index.ts\n * @description MCP Prompts exposed by the BrandKit server.\n *\n * Prompts are reusable, parameterized message templates that surface in\n * MCP-compatible clients (e.g. Claude Desktop's slash menu) so users can\n * invoke common brand-aware workflows in one click.\n */\n\nimport type { DesignSystemIndex } from '../indexer/types.js';\n\ninterface PromptArg {\n  name: string;\n  description: string;\n  required?: boolean;\n}\n\ninterface PromptDescriptor {\n  name: string;\n  description: string;\n  arguments?: PromptArg[];\n}\n\n// v2 prompts: context values are 'base' | 'web' | 'product' (not 'marketing' | 'shared').\n// Tool names updated: get_colors_and_type (replaces get_colors + get_typography),\n// get_assets (replaces get_logos + get_textures), get_voice (replaces get_guidelines section \"brand-voice\").\nconst PROMPTS: PromptDescriptor[] = [\n  {\n    name: 'design-with-brand',\n    description: 'Build a UI feature using the brand design system. Auto-injects colors, typography, and component conventions for the given context.',\n    arguments: [\n      { name: 'feature', description: 'What you want to build (e.g. \"pricing page hero\")', required: true },\n      { name: 'context', description: 'base | web | product', required: false },\n    ],\n  },\n  {\n    name: 'audit-brand-compliance',\n    description: 'Audit a snippet of CSS/HTML/JSX for brand compliance. Flags non-brand colors, fonts, and unapproved asset usage.',\n    arguments: [\n      { name: 'snippet', description: 'The code to audit', required: true },\n      { name: 'context', description: 'base | web | product', required: false },\n    ],\n  },\n  {\n    name: 'generate-tailwind-theme',\n    description: 'Generate a Tailwind v3 / v4 theme extension that mirrors the current brand tokens.',\n    arguments: [\n      { name: 'context', description: 'base | web | product', required: false },\n    ],\n  },\n  {\n    name: 'explain-brand-decision',\n    description: 'Explain how a particular brand-system rule should be applied for a given scenario.',\n    arguments: [\n      { name: 'topic', description: 'e.g. \"logo on photography\", \"error states\", \"headline hierarchy\"', required: true },\n    ],\n  },\n];\n\nexport function listPrompts(): PromptDescriptor[] {\n  return PROMPTS;\n}\n\nexport function getPrompt(\n  name: string,\n  args: Record<string, string>,\n  index: DesignSystemIndex,\n): { description?: string; messages: Array<{ role: 'user' | 'assistant'; content: { type: 'text'; text: string } }> } {\n  const ctx = args.context ?? 'base';\n  const brandName = index.brandName;\n\n  // Get color custom properties from the appropriate context for hints\n  const ctxData = ctx === 'web' ? index.web\n                : ctx === 'product' ? index.product\n                : index.base;\n  const customProps = ctxData.colorsAndType?.customProperties ?? index.base.colorsAndType?.customProperties ?? {};\n  const colorHints = Object.entries(customProps)\n    .filter(([k]) => k.startsWith('--color'))\n    .slice(0, 20)\n    .map(([k, v]) => `- ${k}: ${v}`)\n    .join('\\n') || '(none)';\n\n  switch (name) {\n    case 'design-with-brand': {\n      const feature = args.feature ?? 'a new UI feature';\n      const text = `You are designing **${feature}** using the ${brandName} brand system (context: ${ctx}).\n\nUse the get_colors_and_type, get_components, get_voice, and get_tokens tools as needed.\n\nColor custom properties (top 20):\n${colorHints}\n\nConstraints:\n- Use only brand-approved colors, fonts, and component patterns.\n- Match the tone defined by the brand voice (get_voice).\n- Call validate_usage to confirm any color/font/asset before finalizing.\n\nNow produce the implementation (HTML + CSS or JSX + Tailwind) for: ${feature}.`;\n      return {\n        description: `Design ${feature} with the ${brandName} brand system`,\n        messages: [{ role: 'user', content: { type: 'text', text } }],\n      };\n    }\n\n    case 'audit-brand-compliance': {\n      const snippet = args.snippet ?? '';\n      const text = `Audit the following code for brand compliance against the ${brandName} design system (context: ${ctx}).\n\nColor custom properties (top 20):\n${colorHints}\n\nFor each issue found, report:\n1. The offending line/value\n2. Why it violates the brand\n3. The closest approved replacement (use validate_usage to verify)\n\nCode:\n\\`\\`\\`\n${snippet}\n\\`\\`\\``;\n      return {\n        description: 'Audit code for brand compliance',\n        messages: [{ role: 'user', content: { type: 'text', text } }],\n      };\n    }\n\n    case 'generate-tailwind-theme': {\n      const text = `Use the get_tokens tool with context=\"${ctx}\" to retrieve the current ${brandName} token specimens, then format them as a complete Tailwind v3 theme extension and a Tailwind v4 \\`@theme\\` block. Also call get_colors_and_type with context=\"${ctx}\" for the CSS custom properties.`;\n      return {\n        description: 'Generate Tailwind theme from brand tokens',\n        messages: [{ role: 'user', content: { type: 'text', text } }],\n      };\n    }\n\n    case 'explain-brand-decision': {\n      const topic = args.topic ?? 'general usage';\n      const text = `Using the get_voice, get_positioning, and search_brand tools, explain how the ${brandName} brand system handles: **${topic}**.\n\nCite the specific document(s) you reference, summarize the rule in one sentence, then give a worked example.`;\n      return {\n        description: `Explain brand decision: ${topic}`,\n        messages: [{ role: 'user', content: { type: 'text', text } }],\n      };\n    }\n\n    default:\n      throw new Error(`Unknown prompt: ${name}`);\n  }\n}\n","/**\n * @file version.ts\n * @description Single source of truth for the package version at runtime.\n * Walks up from the compiled module location looking for package.json so it\n * works from src/ (vitest), dist/ (tsup output), and bundled CLI layouts.\n *\n * NOTE: src/adapters/cloudflare-worker.ts cannot use this module (Workers\n * have no fs); it carries a hardcoded version updated at release time.\n */\n\nimport { readFileSync, existsSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\n\nexport function getPackageVersion(): string {\n  try {\n    const here = dirname(fileURLToPath(import.meta.url));\n    const candidates = [\n      join(here, '../package.json'),\n      join(here, '../../package.json'),\n      join(here, '../../../package.json'),\n    ];\n    for (const c of candidates) {\n      if (existsSync(c)) {\n        try {\n          return JSON.parse(readFileSync(c, 'utf-8')).version as string;\n        } catch {\n          // unreadable/corrupt candidate; try the next one\n        }\n      }\n    }\n  } catch {\n    // import.meta.url unavailable in unusual runtimes\n  }\n  return '0.0.0';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACH9D,uBAAwB;;;ACTxB,gBAQO;AACP,kBAA0C;AAC1C,iBAA8B;AAC9B,qBAAiB;AAEjB,SAAS,mBAA2B;AAClC,QAAM,WAAO,yBAAQ,0BAAc,aAAe,CAAC;AACnD,QAAM,aAAa;AAAA,QACjB,kBAAK,MAAM,6CAA6C;AAAA,QACxD,kBAAK,MAAM,gDAAgD;AAAA,QAC3D,kBAAK,MAAM,mDAAmD;AAAA,EAChE;AACA,aAAW,KAAK,YAAY;AAC1B,YAAI,sBAAW,CAAC,EAAG,QAAO;AAAA,EAC5B;AACA,QAAM,IAAI;AAAA,IACR,wDAAwD,WAAW,KAAK,IAAI,CAAC;AAAA,EAC/E;AACF;AAEA,SAAS,cAAc,KAAa,KAAmB;AACrD,2BAAU,KAAK,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AU,MAAM,WAAW,EAAE,SAAS,CAAC,CAAC;AAC5F,IAAM,gBAAgB,SAAS,SAAS,KAAK,cAAc,IAAI,SAAS,CAAC,CAAC;AAC1E,IAAI,CAAC,iBAAiB,CAAC,iBAAiB;AAEtC,UAAQ,KAAK,OAAO,GAAG,GAAG,OAAO;AACnC;AAEA,QAAQ,MAAM;","names":["yaml","import_fs","import_path","import_fs","import_path","import_url","import_js_yaml","yaml","import_fs","import_path","import_fs","matter","import_fs","import_js_yaml","import_fs","import_path","import_gray_matter","import_fs","import_path","matter","matter","import_fs","import_path","import_fs","import_path","import_path","chokidar","import_path","import_url","import_fs","__filename","express","ejs","import_server","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","CONTEXTS","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","INPUT_SCHEMA","TOOL_DESCRIPTION","TOOL_NAME","handler","TOOL_NAME","TOOL_DESCRIPTION","INPUT_SCHEMA","handler","handler","TOOL_NAME","handler","import_path","import_url","import_fs","import_path","import_url","express"]}