Repository navigation
Expand file tree
/
Copy pathvalidate-frontmatter.js
More file actions
560 lines (486 loc) · 17.2 KB
/
Copy pathvalidate-frontmatter.js
File metadata and controls
560 lines (486 loc) · 17.2 KB
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
#!/usr/bin/env node
/**
* Frontmatter validation runner covering markdown and YAML files across the repo.
* Ensures compliance with the shared frontmatter schema.
*
* @module scripts/validation/validate-frontmatter
* @fileoverview Comprehensive frontmatter validation for LightSpeedWP .github repository
* @see .schemas/frontmatter.schema.json
* @author LightSpeedWP Team
* @version 1.0.0
*/
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const yaml = require('js-yaml');
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const glob = require('glob');
const { minimatch } = require('minimatch');
// Configuration
const CONFIG = {
schemaPath: path.join(__dirname, '../../.schemas/frontmatter.schema.json'),
rootDir: path.join(__dirname, '../..'),
logDir: path.join(__dirname, '../../logs/validation'),
outputFile: path.join(__dirname, '../../logs/validation/frontmatter-validation.log'),
patterns: [
'**/*.md',
'**/*.yml',
'**/*.yaml',
'.github/**/*.md',
'.github/**/*.yml',
'.github/**/*.yaml',
],
excludePatterns: ['node_modules/**', '.git/**', 'coverage/**', 'logs/**', '**/package-lock.json'],
targetFiles: [],
};
// Logging utility
class Logger {
constructor(logFile) {
this.logFile = logFile;
this.logs = [];
// Ensure log directory exists
const logDir = path.dirname(logFile);
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
}
log(level, message, file = null, details = null) {
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
level,
message,
file,
details,
};
this.logs.push(logEntry);
// Console output with color coding
const colors = {
ERROR: '\x1b[31m', // Red
WARN: '\x1b[33m', // Yellow
INFO: '\x1b[36m', // Cyan
SUCCESS: '\x1b[32m', // Green
RESET: '\x1b[0m',
};
const color = colors[level] || colors.RESET;
const fileInfo = file ? ` [${path.relative(CONFIG.rootDir, file)}]` : '';
console.log(`${color}[${level}]${colors.RESET} ${message}${fileInfo}`);
if (details) {
console.log(` ${JSON.stringify(details, null, 2)}`);
}
}
error(message, file, details) {
this.log('ERROR', message, file, details);
}
warn(message, file, details) {
this.log('WARN', message, file, details);
}
info(message, file, details) {
this.log('INFO', message, file, details);
}
success(message, file, details) {
this.log('SUCCESS', message, file, details);
}
writeToFile() {
const logContent = this.logs
.map(
(entry) =>
`[${entry.timestamp}] ${entry.level}: ${entry.message}` +
(entry.file ? ` [${entry.file}]` : '') +
(entry.details ? `\n Details: ${JSON.stringify(entry.details)}` : '')
)
.join('\n');
fs.writeFileSync(this.logFile, logContent);
this.info(`Validation log written to: ${this.logFile}`);
}
}
// Frontmatter extractor
class FrontmatterExtractor {
static extract(content, filePath) {
const yamlFrontmatterRegex = /^---\n([\s\S]*?)\n---/;
const match = content.match(yamlFrontmatterRegex);
if (!match) {
return { frontmatter: null, hasYamlBlock: false };
}
try {
const frontmatter = yaml.load(match[1]);
return { frontmatter, hasYamlBlock: true };
} catch (error) {
throw new Error(`Invalid YAML frontmatter in ${filePath}: ${error.message}`, {
cause: error,
});
}
}
}
// Validation engine
class FrontmatterValidator {
constructor(schemaPath, logger) {
this.logger = logger;
this.schema = this.loadSchema(schemaPath);
this.ajv = new Ajv({ allErrors: true, verbose: true, strict: false });
addFormats(this.ajv);
this.validate = this.ajv.compile(this.schema);
this.stats = {
total: 0,
validated: 0,
errors: 0,
warnings: 0,
skipped: 0,
};
}
loadSchema(schemaPath) {
try {
const schemaContent = fs.readFileSync(schemaPath, 'utf8');
return JSON.parse(schemaContent);
} catch (error) {
throw new Error(`Failed to load schema from ${schemaPath}: ${error.message}`, {
cause: error,
});
}
}
validateFile(filePath) {
this.stats.total++;
try {
const content = fs.readFileSync(filePath, 'utf8');
const { frontmatter, hasYamlBlock } = FrontmatterExtractor.extract(content, filePath);
// Skip files without frontmatter for certain file types
if (!hasYamlBlock) {
const shouldHaveFrontmatter = this.shouldHaveFrontmatter(filePath);
if (shouldHaveFrontmatter) {
this.logger.warn('Missing frontmatter', filePath, {
reason: 'File should have frontmatter according to LightSpeed standards',
fileType: this.getFileType(filePath),
});
this.stats.warnings++;
} else {
this.stats.skipped++;
}
return;
}
// Validate frontmatter against schema
const isValid = this.validate(frontmatter);
if (isValid) {
this.logger.success('Valid frontmatter', filePath);
this.stats.validated++;
} else {
this.logger.error('Invalid frontmatter', filePath, {
errors: this.validate.errors.map((error) => ({
instancePath: error.instancePath,
schemaPath: error.schemaPath,
keyword: error.keyword,
params: error.params,
message: error.message,
})),
});
this.stats.errors++;
}
// Additional LightSpeed-specific validations
this.performLightSpeedValidations(frontmatter, filePath);
} catch (error) {
this.logger.error('Validation failed', filePath, {
error: error.message,
});
this.stats.errors++;
}
}
shouldHaveFrontmatter(filePath) {
// Define file patterns that should have frontmatter
const shouldHavePatterns = [
/\.github\/agents\//,
/\.github\/chatmodes\//,
/\.github\/instructions\//,
/\.github\/prompts\//,
/\.github\/collections\//,
/\.github\/ISSUE_TEMPLATE\//,
/\.github\/PULL_REQUEST_TEMPLATE\//,
/\.github\/DISCUSSION_TEMPLATE\//,
/\.github\/SAVED_REPLIES\//,
/README\.md$/,
/\.github\/[^/]+\.md$/, // Main .github files
];
return shouldHavePatterns.some((pattern) => pattern.test(filePath));
}
getFileType(filePath) {
if (filePath.includes('/agents/') || filePath.includes('/.github/agents/')) return 'agent';
if (filePath.includes('/.github/chatmodes/')) return 'chatmode';
if (filePath.includes('/.github/instructions/')) return 'instruction';
if (filePath.includes('/.github/prompts/')) return 'prompt';
if (filePath.includes('/.github/collections/')) return 'collection';
if (filePath.includes('/ISSUE_TEMPLATE/')) return 'issue_template';
if (filePath.includes('/PULL_REQUEST_TEMPLATE/')) return 'pull_request_template';
if (filePath.includes('/DISCUSSION_TEMPLATE/')) return 'discussion_template';
if (filePath.includes('/SAVED_REPLIES/')) return 'saved_reply';
if (filePath.endsWith('README.md')) return 'readme';
if (filePath.includes('/.github/') && filePath.endsWith('.md')) return 'documentation';
return 'unknown';
}
performLightSpeedValidations(frontmatter, filePath) {
const fileType = this.getFileType(filePath);
// Ensure the removed `references` field is not present
if (frontmatter && Object.prototype.hasOwnProperty.call(frontmatter, 'references')) {
this.logger.error(
"The frontmatter 'references' field has been removed; convert any links to inline citations instead.",
filePath
);
this.stats.errors++;
}
// Check for required fields based on file type
const requiredFields = this.getRequiredFieldsByType(fileType);
const missingFields = requiredFields.filter(
(field) =>
!Object.prototype.hasOwnProperty.call(frontmatter, field) ||
frontmatter[field] === null ||
frontmatter[field] === undefined ||
frontmatter[field] === ''
);
if (missingFields.length > 0) {
this.logger.warn('Missing required fields', filePath, {
fileType,
missingFields,
recommendation: `Add the following fields: ${missingFields.join(', ')}`,
});
this.stats.warnings++;
}
// Check for recommended fields
const recommendedFields = this.getRecommendedFieldsByType(fileType);
const missingRecommended = recommendedFields.filter(
(field) => !Object.prototype.hasOwnProperty.call(frontmatter, field)
);
if (missingRecommended.length > 0) {
this.logger.info('Missing recommended fields', filePath, {
fileType,
missingRecommended,
suggestion: `Consider adding: ${missingRecommended.join(', ')}`,
});
}
}
getRequiredFieldsByType(fileType) {
const requirements = {
agent: ['file_type', 'name', 'description'],
chatmode: ['file_type', 'description'],
instruction: ['file_type', 'description'], // apply_to/applyTo verified separately if present
prompt: ['file_type', 'description'],
collection: ['file_type', 'name', 'description'],
issue_template: ['file_type', 'name', 'about'],
pull_request_template: ['file_type', 'title'],
discussion_template: ['file_type', 'name', 'description'],
saved_reply: ['file_type', 'title'],
readme: ['file_type', 'title', 'description'],
documentation: ['file_type', 'description'],
};
return requirements[fileType] || ['file_type'];
}
getRecommendedFieldsByType(fileType) {
const recommendations = {
agent: ['version', 'last_updated', 'owners', 'tags'],
chatmode: ['tools', 'model', 'owners', 'tags', 'context_window', 'temperature', 'max_tokens'],
instruction: ['owners', 'tags', 'version'],
prompt: ['mode', 'model', 'tools', 'tags'],
collection: ['version', 'last_updated', 'tags'],
readme: ['version', 'last_updated', 'owners', 'tags'],
documentation: ['owners', 'tags'],
};
return recommendations[fileType] || ['owners', 'tags'];
}
getStats() {
return { ...this.stats };
}
}
// File discovery
class FileDiscovery {
static findFiles(patterns, excludePatterns, rootDir) {
const allFiles = [];
patterns.forEach((pattern) => {
const files = glob.sync(pattern, {
cwd: rootDir,
ignore: excludePatterns,
absolute: true,
});
allFiles.push(...files);
});
// Remove duplicates and sort
return [...new Set(allFiles)].sort();
}
/**
* Returns only the files changed between two git SHAs that match the given
* patterns and are not excluded. Falls back to findFiles() when git is
* unavailable or the range cannot be resolved.
*
* @param {string} baseSha - Base commit SHA.
* @param {string} headSha - Head commit SHA.
* @param {string[]} patterns - Glob patterns to match (e.g. ["**\/*.md"]).
* @param {string[]} excludePatterns - Glob patterns to exclude.
* @param {string} rootDir - Repository root directory.
* @returns {string[]} Absolute paths of changed, matching files.
*/
static findChangedFiles(baseSha, headSha, patterns, excludePatterns, rootDir) {
// Validate SHAs to prevent shell injection — must be 4–64 hex characters
const shaRe = /^[0-9a-f]{4,64}$/i;
if (!shaRe.test(baseSha) || !shaRe.test(headSha)) {
console.warn('Invalid SHA format for --base/--head; falling back to full validation.');
return FileDiscovery.findFiles(patterns, excludePatterns, rootDir);
}
let changedRelative;
try {
const output = execFileSync(
'git',
['diff', '--name-only', '--diff-filter=ACMRT', baseSha, headSha],
{ cwd: rootDir, encoding: 'utf8' }
);
changedRelative = output
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
} catch {
// git unavailable or SHA range invalid — fall back to full scan
return FileDiscovery.findFiles(patterns, excludePatterns, rootDir);
}
if (!changedRelative.length) {
return [];
}
// Filter changed paths directly against patterns/excludes without a full
// filesystem walk, keeping work proportional to diff size rather than repo size.
const mmOpts = { dot: true };
return changedRelative
.filter((rel) => {
const matched = patterns.some((p) => minimatch(rel, p, mmOpts));
if (!matched) return false;
return !excludePatterns.some((p) => minimatch(rel, p, mmOpts));
})
.map((rel) => path.resolve(rootDir, rel))
.sort();
}
}
function resolveCliTargetFiles(fileArgs, rootDir) {
if (!Array.isArray(fileArgs) || fileArgs.length === 0) {
return [];
}
return [
...new Set(
fileArgs.map((filePath) =>
path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath)
)
),
].filter((filePath) => fs.existsSync(filePath));
}
function runAltValidation() {
try {
const schemaContent = fs.readFileSync(CONFIG.schemaPath, 'utf8');
const schema = JSON.parse(schemaContent);
const files = FileDiscovery.findFiles(CONFIG.patterns, CONFIG.excludePatterns, CONFIG.rootDir);
console.log('Alt frontmatter validation placeholder.');
console.log(`Schema title: ${schema.title || 'unknown'} | Files discovered: ${files.length}`);
process.exit(0);
} catch (error) {
console.error('Alt frontmatter validation failed:', error.message);
process.exit(1);
}
}
// Main validation function
async function validateFrontmatter(filePaths) {
const logger = new Logger(CONFIG.outputFile);
logger.info('Starting frontmatter validation', null, {
schema: CONFIG.schemaPath,
rootDir: CONFIG.rootDir,
patterns: CONFIG.patterns,
excludePatterns: CONFIG.excludePatterns,
targetFiles: CONFIG.targetFiles,
});
try {
// Initialize validator
const validator = new FrontmatterValidator(CONFIG.schemaPath, logger);
// Discover files — use provided list or fall back to full discovery
const files =
filePaths || FileDiscovery.findFiles(CONFIG.patterns, CONFIG.excludePatterns, CONFIG.rootDir);
logger.info(`Found ${files.length} files to validate`);
// Validate each file
files.forEach((file) => {
validator.validateFile(file);
});
// Generate summary
const stats = validator.getStats();
logger.info('Validation completed', null, stats);
// Write log file
logger.writeToFile();
// Set the exit code instead of calling process.exit(): with piped
// stdout, exit() can drop buffered output, which cut the final
// "Validation log written to:" line intermittently.
const hasErrors = stats.errors > 0;
process.exitCode = hasErrors ? 1 : 0;
} catch (error) {
logger.error('Validation failed', null, { error: error.message });
logger.writeToFile();
process.exitCode = 1;
}
}
// CLI interface
if (require.main === module) {
const args = process.argv.slice(2);
const altMode = args.includes('--alt');
if (args.includes('--help') || args.includes('-h')) {
console.log(`
Frontmatter Validation Script
Usage: node validate-frontmatter.js [options]
Options:
--help, -h Show this help message
--schema PATH Custom schema file path
--root PATH Custom root directory
--output PATH Custom output log file
--base SHA Base commit SHA (used with --head to validate only changed files)
--head SHA Head commit SHA (used with --base to validate only changed files)
Examples:
node validate-frontmatter.js
node validate-frontmatter.js --schema ./custom-schema.json
node validate-frontmatter.js --root /path/to/repo --output ./validation.log
node validate-frontmatter.js --base abc1234 --head def5678
`);
process.exit(0);
}
// Parse command line arguments
const schemaIndex = args.indexOf('--schema');
if (schemaIndex !== -1 && args[schemaIndex + 1]) {
CONFIG.schemaPath = path.resolve(args[schemaIndex + 1]);
}
const rootIndex = args.indexOf('--root');
if (rootIndex !== -1 && args[rootIndex + 1]) {
CONFIG.rootDir = path.resolve(args[rootIndex + 1]);
}
const outputIndex = args.indexOf('--output');
if (outputIndex !== -1 && args[outputIndex + 1]) {
CONFIG.outputFile = path.resolve(args[outputIndex + 1]);
}
const baseIndex = args.indexOf('--base');
const baseSha = baseIndex !== -1 ? args[baseIndex + 1] : null;
const headIndex = args.indexOf('--head');
const headSha = headIndex !== -1 ? args[headIndex + 1] : null;
if (altMode) {
runAltValidation();
} else if (baseSha && headSha) {
// Validate only files changed between the two SHAs
const changedFiles = FileDiscovery.findChangedFiles(
baseSha,
headSha,
CONFIG.patterns,
CONFIG.excludePatterns,
CONFIG.rootDir
);
validateFrontmatter(changedFiles).catch((err) => {
console.error('Frontmatter validation error:', err?.stack ?? String(err));
process.exit(1);
});
} else {
validateFrontmatter().catch((err) => {
console.error('Frontmatter validation error:', err?.stack ?? String(err));
process.exit(1);
});
}
}
module.exports = {
FrontmatterValidator,
FrontmatterExtractor,
FileDiscovery,
Logger,
CONFIG,
resolveCliTargetFiles,
};