summaryrefslogtreecommitdiff
path: root/scripts/validate-commands.js
blob: ebd0a1e0a1c48e9b7af1d00238de82d81db5b280 (plain)
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
#!/usr/bin/env node
/**
 * validate-commands.js
 *
 * Guards against silent drift across the three slash-command directories:
 *   .claude/commands/  (.md — Claude Code)
 *   .gemini/commands/  (.toml — Gemini CLI)
 *   commands/          (.toml — Antigravity CLI)
 *
 * Checks (errors block CI):
 *   - Every command present in one directory exists in all three
 *   - The 'description' field is identical across all three equivalents
 *   - Claude command frontmatter is valid YAML, not merely splittable
 *
 * What this does NOT check:
 *   Prompt body differences are intentional — each tool has its own
 *   syntax ($ARGUMENTS, agent-skills: prefixes, GEMINI.md vs CLAUDE.md).
 *
 * Exit codes: 0 = all clear, 1 = one or more errors
 */

'use strict';

const fs   = require('fs');
const path = require('path');

// The same frontmatter-validity rules validate-skills applies to SKILL.md.
// Description extraction shares the top-level frontmatter reader with skills.
// YAML validity is checked separately because Claude Code parses frontmatter
// when the command is loaded. The #494 thread verified all 25 SKILL.md files
// and the command files by hand; this makes the second half a check too.
const { frontmatterYamlErrors, parseFrontmatter } = require(path.join(__dirname, 'lib', 'skill-lint.js'));

// ─── Config ───────────────────────────────────────────────────────────────────

const ROOT = path.resolve(__dirname, '..');

const DIRS = {
  claude:     { dir: path.join(ROOT, '.claude', 'commands'), ext: '.md'   },
  gemini:     { dir: path.join(ROOT, '.gemini', 'commands'), ext: '.toml' },
  antigravity:{ dir: path.join(ROOT, 'commands'),            ext: '.toml' },
};

// Commands where the file stem differs between Claude and the TOML dirs.
// Key = Claude stem, value = TOML stem.
const NAME_MAP = {
  plan: 'planning',
};
const NAME_MAP_REVERSE = Object.fromEntries(
  Object.entries(NAME_MAP).map(([k, v]) => [v, k])
);

// ─── Parsers ──────────────────────────────────────────────────────────────────

function descriptionFromMd(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  return parseFrontmatter(content)?.description ?? null;
}

function descriptionFromToml(filePath) {
  const content     = fs.readFileSync(filePath, 'utf8');
  const doubleMatch = content.match(/^description\s*=\s*"((?:[^"\\]|\\.)*)"/m);
  if (doubleMatch) return doubleMatch[1].replace(/\\"/g, '"');
  const singleMatch = content.match(/^description\s*=\s*'([^']*)'/m);
  return singleMatch ? singleMatch[1] : null;
}

// ─── Loader ───────────────────────────────────────────────────────────────────

function loadCommands({ dir, ext }) {
  if (!fs.existsSync(dir)) return {};
  return Object.fromEntries(
    fs.readdirSync(dir)
      .filter(f => f.endsWith(ext))
      .map(f => {
        const stem = path.basename(f, ext);
        const full = path.join(dir, f);
        try {
          const desc = ext === '.md' ? descriptionFromMd(full) : descriptionFromToml(full);
          return [stem, desc];
        } catch (e) {
          console.log(`  ✗  ${stem} — cannot read file: ${e.message}`);
          return [stem, null];
        }
      })
  );
}

// ─── Main ─────────────────────────────────────────────────────────────────────

function main() {
  const byTool = {
    claude:      loadCommands(DIRS.claude),
    gemini:      loadCommands(DIRS.gemini),
    antigravity: loadCommands(DIRS.antigravity),
  };

  // Canonical command list: use Claude stems as the reference.
  // Map each Claude stem to its TOML equivalent for lookup.
  const claudeStems = Object.keys(byTool.claude).sort();
  const allTomlStems = new Set([
    ...Object.keys(byTool.gemini),
    ...Object.keys(byTool.antigravity),
  ]);
  const allCanonicalStems = new Set([
    ...claudeStems,
    ...[...allTomlStems].map(s => NAME_MAP_REVERSE[s] ?? s),
  ]);

  let errors = 0;

  // ── Parity check ────────────────────────────────────────────────────────────
  console.log('Checking command parity...');

  // Commands in Claude not found in TOML dirs
  for (const stem of claudeStems) {
    const tomlStem = NAME_MAP[stem] ?? stem;
    const missing  = [];
    if (!(tomlStem in byTool.gemini))      missing.push('.gemini/commands');
    if (!(tomlStem in byTool.antigravity)) missing.push('commands');
    if (missing.length) {
      console.log(`  ✗  ${stem} — missing in: ${missing.join(', ')}`);
      errors++;
    } else {
      console.log(`  ✓  ${stem}${stem !== tomlStem ? ` (${tomlStem} in toml dirs)` : ''}`);
    }
  }

  // Commands in TOML dirs not found in Claude
  for (const stem of [...allTomlStems].sort()) {
    const claudeStem = NAME_MAP_REVERSE[stem] ?? stem;
    if (!(claudeStem in byTool.claude)) {
      console.log(`  ✗  ${stem} — present in toml dirs but missing in .claude/commands`);
      errors++;
    }
  }

  // ── Claude frontmatter validity ─────────────────────────────────────────────
  // Only the .md directory: the TOML dirs are parsed by a real TOML parser
  // already, so a malformed one surfaces as a missing description above.
  console.log('\nChecking Claude command frontmatter...');

  for (const stem of claudeStems) {
    const full = path.join(DIRS.claude.dir, `${stem}${DIRS.claude.ext}`);
    let yamlErrors = [];
    try {
      yamlErrors = frontmatterYamlErrors(fs.readFileSync(full, 'utf8'));
    } catch (e) {
      console.log(`  ✗  ${stem} — cannot read file: ${e.message}`);
      errors++;
      continue;
    }
    if (yamlErrors.length === 0) {
      console.log(`  ✓  ${stem}`);
      continue;
    }
    console.log(`  ✗  ${stem}`);
    for (const message of yamlErrors) {
      console.log(`       ${message}`);
      errors++;
    }
  }

  // ── Description sync check ──────────────────────────────────────────────────
  console.log('\nChecking description sync...');

  for (const claudeStem of claudeStems) {
    const tomlStem   = NAME_MAP[claudeStem] ?? claudeStem;
    const descClaude = byTool.claude[claudeStem];
    const descGemini = byTool.gemini[tomlStem];
    const descAgy    = byTool.antigravity[tomlStem];

    const malformed = [
      ['.claude/commands', byTool.claude, claudeStem],
      ['.gemini/commands', byTool.gemini, tomlStem],
      ['commands/', byTool.antigravity, tomlStem],
    ].filter(([, commands, stem]) => Object.prototype.hasOwnProperty.call(commands, stem) && commands[stem] == null);

    if (malformed.length) {
      console.log(`  ✗  ${claudeStem}`);
      for (const [toolDir, , stem] of malformed) {
        console.log(`       ${toolDir}/${stem} — missing or malformed description`);
      }
      errors++;
      continue;
    }

    if (descClaude == null || descGemini == null || descAgy == null) {
      // Missing file already flagged by parity check
      continue;
    }

    const allMatch = descClaude === descGemini && descGemini === descAgy;

    if (allMatch) {
      console.log(`  ✓  ${claudeStem}`);
    } else {
      console.log(`  ✗  ${claudeStem}`);
      console.log(`       .claude:      ${descClaude}`);
      console.log(`       .gemini:      ${descGemini}`);
      console.log(`       commands/:    ${descAgy}`);
      errors++;
    }
  }

  const status = errors > 0 ? 'FAILED' : 'PASSED';
  console.log(`\n${allCanonicalStems.size} commands checked — ${errors} error(s) — ${status}`);

  if (errors > 0) process.exit(1);
}

main();