# All files / lib/visualizers index.js

78.08% Statements 139/178
66.46% Branches 111/167
71.42% Functions 20/28
80.23% Lines 138/172

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907

    2x
    2x

    6x
    6x
    5x

    1x

    12x
    12x

    12x
    12x

    12x

    1x
    1x

    11x

    11x
    11x

    9x

    2x
    2x

    15x
    15x

    14x
    15x

    15x

    6x
    9x

    9x
    9x

    9x

    8x
    8x

    8x
    2x
    1x

    1x

    6x

    8x
    8x
    8x

    11x

    11x

    11x

    11x
    1x

    10x

    10x
    10x
    1x

    9x

    11x

    21x
    1x

    20x

    20x

    20x
    46x
    46x
    32x

    20x

    15x

    15x

    14x

    13x

    13x
    13x

    1x

    13x

    8x

    8x
    24x
    24x
    15x
    15x
    15x
    15x
    15x
    15x

    8x
    8x
    8x

    8x
    8x
    11x
    11x

    8x

    8x

    8x
    8x
    8x

    8x

    11x
    11x

    11x
    11x
    13x
    13x

    11x
    11x
    13x
    13x

    8x

    8x
    8x
    8x
    8x
    8x

    8x
    8x
    8x
    8x

    8x
    8x
    8x

    8x

    2x

    2x
    20x
    20x
    20x

    2x
    2x
    2x
    2x

    2x

    2x

    2x

    23x

    2x

    2x

    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

     import fs from 'fs-extra';
    import path from 'path';
    import { fileURLToPath } from 'url';
    import { escapeJsonForScript, openBrowser, escapeHtml } from './utils.js';
    import { loadManifest } from '../skills-manifest.js';
    import { loadCatalog } from '../catalog.js';
    import { detectIdes } from '../context.js';
    import { TARGETS } from '../constants.js';

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);

    /**
     * Load installed skills from .rosetta/skills/manifest.json
     * Returns array of skill objects with status='installed'
     *
     * @returns {Promise<Array>} - Array of transformed skill objects
     */
    export async function loadInstalledSkills() {
      try {
        const manifest = await loadManifest();
        return manifest.installed.map(skill => ({
          ...skill,
          status: 'installed',
          id: skill.name.toLowerCase(),
          description: skill.description || '',
          domains: skill.domains || [],
          tags: skill.tags || [],
          provides: skill.provides || [],
          requires: skill.requires || [],
          ideCompatibility: skill.ideCompatibility || ['all'],
          repoUrl: skill.repoUrl || '',
          source: 'manifest'
        }));
      } catch (err) {
        // If manifest doesn't exist or is invalid, return empty array
        return [];
      }
    }

    /**
     * Parses a skill file (SKILL.md or *.skill.md) to extract frontmatter metadata
     * Supports JSON frontmatter between --- delimiters
     *
     * @param {string} filePath - Path to the skill file
     * @returns {Promise<Object>} - Parsed metadata object with standardized fields
     */
    export async function parseSkillFile(filePath) {
      try {
        const content = await fs.readFile(filePath, 'utf8');

        // Find frontmatter between --- delimiters (first occurrence only)
        const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
        const rawYaml = frontmatterMatch ? frontmatterMatch[1].trim() : null;

        if (!frontmatterMatch) {
          // No frontmatter found - derive name from directory
          const dirName = path.basename(path.dirname(filePath));
          return {
            name: dirName,
            description: 'User-created skill',
            rawYaml: null
          };
        }

        const frontmatterStr = frontmatterMatch[1].trim();

        try {
          const metadata = JSON.parse(frontmatterStr);

          return {
            name: metadata.name || path.basename(path.dirname(filePath)),
            description: metadata.description || '',
            domains: Array.isArray(metadata.domains) ? metadata.domains : [],
            tags: Array.isArray(metadata.tags) ? metadata.tags : [],
            provides: Array.isArray(metadata.provides) ? metadata.provides : [],
            requires: Array.isArray(metadata.requires) ? metadata.requires : [],
            repoUrl: metadata.repoUrl || '',
            rawYaml // Store raw YAML/JSON for display
          };
        } catch (parseErr) {
          // Malformed JSON - return fallback with raw content if possible
          const dirName = path.basename(path.dirname(filePath));
          return {
            name: dirName,
            description: 'User-created skill (malformed metadata)',
            rawYaml: frontmatterStr
          };
        }
      } catch (err) {
        // File read error - return fallback
        const dirName = path.basename(path.dirname(filePath));
        return {
          name: dirName,
          description: 'User-created skill',
          rawYaml: null
        };
      }
    }

    /**
     * Recursively scans a directory to find skill files (SKILL.md, skill.md, or *.skill.md)
     * Collects all skill files at any depth within the given root directory
     *
     * @param {string} rootDir - Root directory to scan recursively
     * @param {Array} allSkills - Accumulator array for found skills
     * @param {Function} parseSkillFile - Parsing function
     * @param {Function} deriveIdeCompatibility - IDE compatibility function
     * @param {number} depth - Current recursion depth (0 for top-level)
     * @returns {Promise<void>}
     */
    async function scanDirectoryRecursive(rootDir, allSkills, parseSkillFile, deriveIdeCompatibility, depth = 0) {
      try {
        const entries = await fs.readdir(rootDir, { withFileTypes: true });

        for (const entry of entries) {
          const fullPath = path.join(rootDir, entry.name);

          if (entry.isDirectory()) {
            // Recurse into subdirectory
            await scanDirectoryRecursive(fullPath, allSkills, parseSkillFile, deriveIdeCompatibility, depth + 1);
          } else Eif (entry.isFile()) {
            // Check if file is a skill file
            const fileName = entry.name;
            const isSkillFile = fileName === 'SKILL.md' ||
                               fileName === 'skill.md' ||
                               fileName.endsWith('.skill.md');

            if (isSkillFile) {
              // Determine skill ID based on location:
              // - If file is directly in the top-level skillsDir (depth 0 and fileDir === rootDir):
              //   * For SKILL.md/skill.md -> 'skill'
              //   * For *.skill.md -> filename without extension
              // - Otherwise (nested in any subdirectory): use the immediate parent directory name
              const fileDir = path.dirname(fullPath);
              const isTopLevelRootFile = depth === 0 && fileDir === rootDir;
              let skillId;

              if (isTopLevelRootFile) {
                if (fileName === 'SKILL.md' || fileName === 'skill.md') {
                  skillId = 'skill';
                } else {
                  skillId = fileName.replace(/\.skill\.md$/, '').toLowerCase();
                }
              } else {
                // File is in a subdirectory - use containing directory name
                skillId = path.basename(fileDir).toLowerCase();
              }

              try {
                const metadata = await parseSkillFile(fullPath);
                allSkills.push({
                  ...metadata,
                  status: 'user-created',
                  id: skillId,
                  source: 'user',
                  path: fileDir,
                  ideCompatibility: deriveIdeCompatibility(metadata.tags || [])
                });
              } catch (parseErr) {
                // Skip this file if parsing fails
                continue;
              }
            }
          }
        }
      } catch (err) {
        // Permission error or other issue - skip this directory
        // No logging to avoid noise for non-existent directories
      }
    }

    /**
     * Loads user-created skills from specified skills directories
     * Scans recursively for SKILL.md or *.skill.md files and parses their frontmatter
     * Automatically excludes templates/skills path to avoid including built-in templates
     *
     * @param {Array<string>} skillsDirs - Directories to scan (default: all IDE-specific skills dirs + common)
     * @returns {Promise<Array>} - Array of transformed user skill objects
     */
    export async function loadUserSkills(skillsDirs = null) {
      // Build default list from TARGETS plus common directories
      Iif (skillsDirs === null) {
        const targetSkillsDirs = TARGETS.map(t => t.skillsDir).filter(dir => dir && !dir.includes('templates/skills'));
        skillsDirs = [...new Set([
          'skills',
          'company-skills',
          '.ai/skills', // Additional common location for AI agent skills
          ...targetSkillsDirs
        ])];
      }

      const allSkills = [];

      for (const dir of skillsDirs) {
        // Skip templates/skills path to avoid including Rosetta's built-in templates
        if (dir.includes('templates/skills') || dir === 'templates/skills') {
          continue;
        }

        try {
          // Check if directory exists
          const exists = await fs.pathExists(dir);
          if (!exists) {
            continue;
          }

          // Recursively scan the directory for skill files
          await scanDirectoryRecursive(dir, allSkills, parseSkillFile, deriveIdeCompatibility);
        } catch (dirErr) {
          // Permission error or other issue - skip this directory
          continue;
        }
      }

      return allSkills;
    }

    /**
     * Loads "Master Skill" style files (AGENTS.md, .cursorrules, etc.)
     * These files usually represent the overall agent logic for a workspace.
     *
     * @returns {Promise<Array>} - Array of skill objects from master files
     */
    export async function loadMasterSkills() {
      const masterFiles = [
        'AGENTS.md',
        '.cursorrules',
        'CLAUDE.md',
        '.ai/master-skill.md',
        'openclaw/AGENTS.md',
        '.rosettablueprint/AGENTS.md'
      ];

      const masterSkills = [];

      for (const fileName of masterFiles) {
        try {
          const fullPath = path.resolve(process.cwd(), fileName);
          const exists = await fs.pathExists(fullPath);

          if (exists) {
            const metadata = await parseSkillFile(fullPath);
            // Specialized logic for master files
            masterSkills.push({
              ...metadata,
              status: 'installed',
              id: `master-${path.basename(fileName).replace(/^\./, '').replace(/\.md$/, '').toLowerCase()}`,
              displayName: `Master: ${fileName}`,
              source: 'master-file',
              ideCompatibility: deriveIdeCompatibility(metadata.tags || [])
            });
          }
        } catch (err) {
          continue;
        }
      }

      return masterSkills;
    }

    /**
     * Derives IDE compatibility from skill tags
     * Scans tags for known IDE keywords and returns array of matching IDE identifiers
     *
     * @param {Array<string>} tags - Array of tag strings
     * @returns {Array<string>} - Array of unique IDE identifiers, defaults to ['all']
     */
    function deriveIdeCompatibility(tags) {
      if (!tags || tags.length === 0) {
        return ['all'];
      }

      const ideMapping = {
        // Distinct IDE identifiers (match template tabs)
        'vscode': 'vscode',
        'cursor': 'cursor',
        'codex': 'codex',
        'kilo-code': 'kilo-code',
        'continue': 'continue',
        'windsurf': 'windsurf',
        'openclaw': 'openclaw',
        // JetBrains umbrella
        'jetbrains': 'jetbrains',
        'intellij': 'jetbrains',
        'pycharm': 'jetbrains',
        // Claude Code
        'claude-code': 'claude-code',
        'anthropic': 'claude-code'
      };

      const ides = new Set();

      for (const tag of tags) {
        const normalizedTag = tag.toLowerCase();
        if (ideMapping[normalizedTag]) {
          ides.add(ideMapping[normalizedTag]);
        }
      }

      return ides.size > 0 ? [...ides] : ['all'];
    }

    /**
     * Loads catalog skills and transforms them to unified schema
     * Uses deriveIdeCompatibility() to compute ideCompatibility from tags
     *
     * @param {Object} catalog - Optional catalog object, loads from default if not provided
     * @returns {Promise<Array>} - Array of transformed catalog skill objects
     */
    export async function loadCatalogSkills(catalog) {
      try {
        // Load catalog if not provided
        const catalogData = catalog || await loadCatalog();

        return catalogData.skills.map((skill, index) => {
          // Use transformCatalogSkill for consistent schema
          const transformed = transformCatalogSkill(skill, index);
          // Override ideCompatibility with derived from tags
          transformed.ideCompatibility = deriveIdeCompatibility(skill.tags || []);
          return transformed;
        });
      } catch (err) {
        // If catalog fails to load, return empty array
        return [];
      }
    }

    /**
     * Transforms a catalog skill into display format
     */
    function transformCatalogSkill(skill, index) {
      return {
        id: skill.name.toLowerCase(),
        name: skill.name,
        displayName: skill.displayName, // undefined if not provided
        description: skill.description || '',
        status: 'catalog',
        ideCompatibility: ['claude-code', 'vscode', 'jetbrains', 'cursor', 'codex', 'kilo-code', 'continue', 'windsurf', 'openclaw'],
        domains: skill.domains || [],
        tags: skill.tags || [],
        repoUrl: skill.repoUrl, // undefined if not provided
        provides: skill.provides || [],
        requires: skill.requires || [],
        author: skill.author, // undefined if not provided
        stars: skill.stars || 0,
        lastUpdated: skill.lastUpdated, // undefined if not provided
        expanded: false,
        source: 'catalog'
      };
    }

    /**
     * Transforms an installed skill from manifest into display format
     */
    function transformInstalledSkill(skill, index) {
      return {
        id: skill.instanceId || `installed-${index}`,
        name: skill.name,
        displayName: skill.name,
        description: `Installed at ${skill.path}`,
        status: skill.tag === 'user-created' ? 'user-created' : 'installed',
        ideCompatibility: ['claude-code', 'vscode', 'jetbrains', 'cursor', 'codex', 'kilo-code', 'continue', 'windsurf', 'openclaw'],
        domains: [],
        tags: skill.tag ? [skill.tag] : [],
        repoUrl: skill.source || null,
        provides: [],
        requires: [],
        scope: skill.scope,
        path: skill.path,
        installedAt: skill.installedAt,
        expanded: false
      };
    }

    /**
     * Detects the current IDE for filtering purposes (normalized ID)
     * Used internally by generateVisualization
     */
    async function _detectCurrentIdeForFilter() {
      try {
        const ides = await detectIdes();

        if (ides.length > 0) {
          const nameToId = {
            'Claude Code': 'claude-code',
            'Cursor': 'cursor',
            'Codex CLI': 'codex',
            'GitHub Copilot': 'copilot',
            'Windsurf': 'windsurf',
            'OpenClaw': 'openclaw',
            'Antigravity': 'antigravity',
            'Generic': 'generic'
          };
          return nameToId[ides[0].name] || 'all';
        }
      } catch (err) {
        // Ignore detection errors
      }
      return 'all';
    }

    /**
     * Detects the current IDE (raw name) for display purposes
     * Returns the detected IDE name or 'auto-detected' if none found
     */
    export async function detectCurrentIde() {
      try {
        const ides = await detectIdes();
        if (ides.length > 0) {
          return ides[0].name;
        }
      } catch (err) {
        // Ignore detection errors
      }
      return 'auto-detected';
    }

    /**
     * Merges skills from installed, catalog, and user sources with deduplication
     * Precedence: installed (3) > user-created (2) > catalog (1)
     * Deduping is case-insensitive on skill name
     *
     * @param {Array} installed - Installed skills
     * @param {Array} catalog - Catalog skills
     * @param {Array} user - User-created skills
     * @returns {Array} - Merged skill array
     */
    export function mergeSkills(installed, catalog, user) {
      const skillMap = new Map();

      const addSkills = (skills, precedence) => {
        Iif (!Array.isArray(skills)) return;
        for (const skill of skills) {
          Iif (!skill || typeof skill !== 'object') continue;
          const key = (skill.name || '').toLowerCase();
          Iif (!key) continue;
          const existing = skillMap.get(key);
          Eif (!existing || precedence > existing._precedence) {
            skillMap.set(key, { ...skill, _precedence: precedence });
          }
        }
      };

      // Add in increasing precedence order so higher overwrites
      addSkills(catalog, 1);
      addSkills(user, 2);
      addSkills(installed, 3);

      const merged = [];
      for (const skill of skillMap.values()) {
        const { _precedence, ...cleanSkill } = skill;
        merged.push(cleanSkill);
      }

      return merged;
    }

    /**
     * Computes statistics for a skill set
     *
     * @param {Array} skills - Array of skill objects
     * @returns {Object} - Stats object with total, byStatus, byDomain, byIde
     */
    export function computeStats(skills) {
      const total = skills.length;

      const byStatus = {};
      const byDomain = {};
      const byIde = {};

      for (const skill of skills) {
        // byStatus
        const status = skill.status || 'unknown';
        byStatus[status] = (byStatus[status] || 0) + 1;

        // byDomain
        Eif (Array.isArray(skill.domains)) {
          for (const domain of skill.domains) {
            Eif (domain) {
              byDomain[domain] = (byDomain[domain] || 0) + 1;
            }
          }
        }

        // byIde
        Eif (Array.isArray(skill.ideCompatibility)) {
          for (const ide of skill.ideCompatibility) {
            Eif (ide) {
              byIde[ide] = (byIde[ide] || 0) + 1;
            }
          }
        }
      }

      return { total, byStatus, byDomain, byIde };
    }

    /**
     * Gathers and processes all skill data for visualization
     * Accepts optional dependency functions for testing (defaults to real implementations)
     *
     * @param {Object} deps - Optional dependencies
     * @param {Function} deps.loadInstalledSkills - Loads installed skills
     * @param {Function} deps.loadCatalogSkills - Loads catalog skills
     * @param {Function} deps.loadUserSkills - Loads user-created skills
     * @param {Function} deps.loadMasterSkills - Loads master skills files
     * @param {Function} deps.detectCurrentIde - Detects current IDE
     * @returns {Promise<Object>} - { skills, stats, currentIde }
     */
    export async function gatherData(deps = {}) {
      // Use dependency injection if provided, otherwise fall back to module defaults
      const _loadInstalledSkills = deps.loadInstalledSkills ?? loadInstalledSkills;
      const _loadCatalogSkills = deps.loadCatalogSkills ?? loadCatalogSkills;
      const _loadUserSkills = deps.loadUserSkills ?? loadUserSkills;
      const _loadMasterSkills = deps.loadMasterSkills ?? loadMasterSkills;
      const _detectCurrentIde = deps.detectCurrentIde ?? detectCurrentIde;

      const installed = await _loadInstalledSkills();
      const catalog = await _loadCatalogSkills();
      const user = await _loadUserSkills();
      const masters = await _loadMasterSkills();

      const merged = mergeSkills(installed, catalog, [...user, ...masters]);
      const stats = computeStats(merged);
      const currentIde = await _detectCurrentIde();

      return {
        skills: merged,
        stats,
        currentIde
      };
    }

    /**
     * Generates IDE tabs HTML
     */
    export function renderIdeTabs(currentIde) {
      const ides = [
        { id: 'all', label: 'All IDEs' },
        { id: 'claude-code', label: 'Claude Code' },
        { id: 'vscode', label: 'VS Code' },
        { id: 'jetbrains', label: 'JetBrains' },
        { id: 'cursor', label: 'Cursor' },
        { id: 'codex', label: 'Codex CLI' },
        { id: 'kilo-code', label: 'Kilo Code' },
        { id: 'continue', label: 'Continue' },
        { id: 'windsurf', label: 'Windsurf' },
        { id: 'openclaw', label: 'OpenClaw' }
      ];

      return ides.map(ide => {
        const activeClass = ide.id === currentIde ? 'active' : '';
        const dataIde = ide.id === 'all' ? 'all' : ide.id;
        return `<button class="ide-tab ${activeClass}" data-ide="${dataIde}">${escapeHtml(ide.label)}</button>`;
      }).join('');
    }

    /**
     * Generates sidebar statistics HTML from stats object
     */
    export function renderSidebarStats(stats) {
      const { total, byStatus, byDomain } = stats;
      const installed = (byStatus.installed || 0) + (byStatus['user-created'] || 0);
      const catalog = byStatus.catalog || 0;
      const domainCount = byDomain ? Object.keys(byDomain).length : 0;

      return `
        <div class="stat-item">
          <span class="stat-label">Total Skills</span>
          <span class="stat-value">${total}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Installed</span>
          <span class="stat-value">${installed}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Available</span>
          <span class="stat-value">${catalog}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Domains</span>
          <span class="stat-value">${domainCount}</span>
        </div>
      `;
    }

    /**
     * Generates search bar HTML fragment
     */
    function generateSearchBarHtml() {
      return `
        <input type="text" id="search-input" placeholder="Search skills by name, description, or tags..." />
        <span class="search-count" id="search-count">Loading...</span>
      `;
    }

    /**
     * Generates skill grid HTML (placeholder, JS renders)
     */
    function generateSkillGridHtml() {
      return '<!-- Skills will be rendered by JavaScript -->';
    }

    /**
     * Prepares skills data for client-side rendering
     */
    function prepareSkillsData(skills, ideFilter) {
      let filteredSkills = skills;
      if (ideFilter && ideFilter !== 'all') {
        filteredSkills = skills.filter(skill =>
          skill.ideCompatibility && skill.ideCompatibility.includes(ideFilter)
        );
      }
      return {
        count: filteredSkills.length,
        skills: filteredSkills
      };
    }

    /**
     * Generates client-side JavaScript for interactivity
     * This script provides search, filtering, and card expansion functionality
     *
     * @returns {string} JavaScript code as a string
     */
    export function renderScript() {
      return `
        (function() {
          let currentIdeFilter = 'all';
          let searchQuery = '';
          let skills = typeof skillsData !== 'undefined' ? skillsData.skills : [];

          // Toggle card expansion
          function toggleCard(id) {
            const skill = skills.find(s => s.id === id);
            if (skill) {
              skill.expanded = !skill.expanded;
              renderGrid();
            }
          }

          // Filter skills based on IDE and search query
          function filterSkills() {
            return skills.filter(skill => {
              const ideMatch = currentIdeFilter === 'all' ||
                               (skill.ideCompatibility && skill.ideCompatibility.includes(currentIdeFilter));
              const searchMatch = searchQuery === '' ||
                                  (skill.name && skill.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
                                  (skill.description && skill.description.toLowerCase().includes(searchQuery.toLowerCase())) ||
                                  (skill.tags && skill.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase())));
              return ideMatch && searchMatch;
            });
          }

          // Render the skill grid
          function renderGrid() {
            const filtered = filterSkills();
            const grid = document.getElementById('skill-grid');
            if (grid) {
              grid.innerHTML = filtered.map(skill => renderSkillCard(skill)).join('');
            }
            updateCounts(filtered.length);
            updateEmptyState(filtered.length);
          }

          // Render a single skill card
          function renderSkillCard(skill) {
            const expandedClass = skill.expanded ? 'expanded' : '';
            const statusBadge = getStatusBadge(skill.status);
            const ideBadges = (skill.ideCompatibility || []).map(ide => \`<span class="ide-badge">\${escapeHtml(ide)}</span>\`).join('');

            if (!skill.expanded) {
              return \`
                <div class="skill-card \${expandedClass}" data-id="\${skill.id}">
                  <div class="card-header">
                    <h3>\${escapeHtml(skill.displayName || skill.name)}</h3>
                    \${statusBadge}
                  </div>
                  <p class="description">\${escapeHtml(truncate(skill.description || '', 120))}</p>
                  <div class="metadata">
                    \${ideBadges}
                  </div>
                </div>
              \`;
            }

            // Expanded view
            return \`
              <div class="skill-card \${expandedClass}" data-id="\${skill.id}">
                <div class="card-header">
                  <h3>\${escapeHtml(skill.displayName || skill.name)}</h3>
                  \${statusBadge}
                </div>
                <div class="card-body">
                  <p class="description">\${escapeHtml(skill.description || '')}</p>

                  <section class="provides">
                    <h4>Provides</h4>
                    <ul>\${(skill.provides || []).map(p => \`<li>\${escapeHtml(p)}</li>\`).join('')}</ul>
                  </section>

                  <section class="requires">
                    <h4>Requires</h4>
                    <ul>\${(skill.requires || []).map(r => \`<li>\${escapeHtml(r)}</li>\`).join('')}</ul>
                  </section>

                  <div class="tags">
                    \${(skill.tags || []).map(tag => \`<span class="tag">\${escapeHtml(tag)}</span>\`).join('')}
                  </div>

                  \${skill.repoUrl ? \`<a href="\${escapeHtml(skill.repoUrl)}" target="_blank" class="repo-link">View Repository →</a>\` : ''}

                  \${skill.rawYaml ? \`
                    <section class="raw-yaml">
                      <h4>Source Metadata</h4>
                      <pre><code>\${escapeHtml(skill.rawYaml)}</code></pre>
                    </section>
                  \` : ''}

                  <button class="collapse-btn" onclick="toggleCard('\${skill.id}')">Show less</button>
                </div>
              </div>
            \`;
          }

          // Generate status badge HTML
          function getStatusBadge(status) {
            const labels = {
              'installed': 'Installed',
              'user-created': 'Custom',
              'catalog': 'Available'
            };
            const label = labels[status] || status;
            return \`<span class="badge badge-\${status}">\${escapeHtml(label)}</span>\`;
          }

          // Update the search count display
          function updateCounts(visibleCount) {
            const countEl = document.getElementById('search-count');
            if (countEl) {
              countEl.textContent = \`\${visibleCount} skill\${visibleCount !== 1 ? 's' : ''}\`;
            }
          }

          // Show/hide empty state
          function updateEmptyState(hasResults) {
            const emptyState = document.getElementById('empty-state');
            if (emptyState) {
              emptyState.style.display = hasResults ? 'none' : 'block';
            }
          }

          // HTML escape utility
          function escapeHtml(str) {
            if (str == null) return '';
            return String(str)
              .replace(/&/g, '&amp;')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, '&#039;');
          }

          // Truncate utility
          function truncate(str, len) {
            if (!str) return '';
            return str.length > len ? str.substring(0, len) + '...' : str;
          }

          // Render domain statistics
          function renderDomainStats() {
            const domainCounts = {};
            skills.forEach(skill => {
              (skill.domains || []).forEach(domain => {
                domainCounts[domain] = (domainCounts[domain] || 0) + 1;
              });
            });
            const domainList = document.getElementById('domain-list');
            if (domainList) {
              domainList.innerHTML = Object.entries(domainCounts)
                .sort((a, b) => b[1] - a[1])
                .map(([domain, count]) => \`<span class="domain-tag">\${escapeHtml(domain)} (\${count})</span>\`).join('');
            }
          }

          // Update IDE tabs active state
          function renderIdeTabs() {
            const tabs = document.querySelectorAll('.ide-tab');
            tabs.forEach(tab => {
              tab.classList.toggle('active', tab.dataset.ide === currentIdeFilter);
            });
            const currentIdeEl = document.getElementById('current-ide');
            if (currentIdeEl) {
              currentIdeEl.textContent = getCurrentIdeLabel();
            }
          }

          // Get human-readable IDE label
          function getCurrentIdeLabel() {
            if (currentIdeFilter === 'all') return 'auto-detected';
            const labels = {
              'vscode': 'VS Code',
              'jetbrains': 'JetBrains',
              'claude-code': 'Claude Code',
              'cursor': 'Cursor',
              'codex': 'Codex CLI',
              'kilo-code': 'Kilo Code',
              'continue': 'Continue',
              'windsurf': 'Windsurf',
              'openclaw': 'OpenClaw'
            };
            return labels[currentIdeFilter] || currentIdeFilter;
          }

          // Initialize on DOM load
          document.addEventListener('DOMContentLoaded', () => {
            renderGrid();
            renderDomainStats();
            renderIdeTabs();

            // Search input handler
            const searchInput = document.getElementById('search-input');
            if (searchInput) {
              searchInput.addEventListener('input', (e) => {
                searchQuery = e.target.value;
                renderGrid();
              });
            }

            // IDE tab click handlers
            const ideTabs = document.querySelectorAll('.ide-tab');
            ideTabs.forEach(tab => {
              tab.addEventListener('click', () => {
                currentIdeFilter = tab.dataset.ide;
                renderIdeTabs();
                renderGrid();
              });
            });

            // Card click delegation
            const grid = document.getElementById('skill-grid');
            if (grid) {
              grid.addEventListener('click', (e) => {
                const card = e.target.closest('.skill-card');
                if (card) {
                  const id = card.dataset.id;
                  toggleCard(id);
                }
              });
            }

            // Escape key to collapse all
            document.addEventListener('keydown', (e) => {
              if (e.key === 'Escape') {
                skills.forEach(s => s.expanded = false);
                renderGrid();
              }
            });
          });
        })();
      `;
    }

    /**
     * Renders the complete HTML page using template and styles
     * This is a modular composition function that assembles the final HTML
     *
     * @param {Object} data - Gathered data from gatherData(): { skills, stats, currentIde }
     * @param {string} template - HTML template string with placeholders
     * @param {string} styles - CSS styles string
     * @param {string} ideFilter - IDE filter ('all' or specific IDE ID)
     * @returns {string} - Complete HTML document
     */
    export function renderHtml(data, template, styles, ideFilter = 'all') {
      const { skills, stats } = data;

      // We inject ALL skills into the HTML, client-side JS handles filtering
      const skillsData = {
        count: skills.length,
        skills: skills
      };

      // Generate HTML components
      const title = 'Rosetta Skills Documentation';
      const sidebarStats = renderSidebarStats(stats);
      const ideTabs = renderIdeTabs(ideFilter);
      const currentIdeDisplay = ideFilter === 'all' ? 'Auto-detected' : ideFilter;
      const searchBar = generateSearchBarHtml();
      const skillGrid = generateSkillGridHtml();
      const skillsJson = escapeJsonForScript(JSON.stringify(skillsData));
      const scriptContent = renderScript();

      // Assemble final HTML by replacing placeholders
      // Note: We do NOT escape styles as they are CSS, not HTML
      return template
        .replace(/{{TITLE}}/g, title)
        .replace(/{{STYLES}}/g, styles)
        .replace(/{{SIDEBAR_STATS}}/g, sidebarStats)
        .replace(/{{IDE_TABS}}/g, ideTabs)
        .replace(/{{CURRENT_IDE}}/g, escapeHtml(currentIdeDisplay))
        .replace(/{{SEARCH_BAR}}/g, searchBar)
        .replace(/{{SKILL_GRID}}/g, skillGrid)
        .replace(/{{SKILLS_JSON}}/g, skillsJson)
        .replace(/{{SCRIPT_CONTENT}}/g, scriptContent);
    }