Repository navigation
Expand file tree
/
Copy pathvalidate-agents.js
More file actions
334 lines (290 loc) · 8.35 KB
/
Copy pathvalidate-agents.js
File metadata and controls
334 lines (290 loc) · 8.35 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
#!/usr/bin/env node
/**
* Validates agent specs against the agent frontmatter schema and organisational rules.
*
* Usage:
* node scripts/validate-agents.js # Validate all agents
* node scripts/validate-agents.js labeling # Validate specific agent
* node scripts/validate-agents.js --json # Output JSON format
*
* @module scripts/validation/validate-agents
* @see agents/agent.md
*/
import fs from 'fs';
import path from 'path';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { load } from 'js-yaml';
import { fileURLToPath } from 'url';
import { globSync } from 'glob';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.join(__dirname, '../..');
const AGENT_DIRS = [
path.join(REPO_ROOT, 'agents'),
path.join(REPO_ROOT, '.github', 'agents'),
].filter((dir) => fs.existsSync(dir));
const SCHEMAS_DIR = path.join(REPO_ROOT, ".schemas");
// Configuration
const args = process.argv.slice(2);
const targetAgent = args.find((a) => !a.startsWith('--'));
const outputJson = args.includes('--json');
const verbose = args.includes('--verbose');
// Initialize Ajv validator
const ajv = new Ajv({ allErrors: true, strict: false });
addFormats(ajv);
// Results tracking
const results = {
total: 0,
valid: 0,
invalid: 0,
skipped: 0,
warnings: 0,
errors: [],
agents: {},
};
/**
* Load JSON schema
*/
function loadSchema(schemaPath) {
try {
const content = fs.readFileSync(schemaPath, 'utf-8');
return JSON.parse(content);
} catch (err) {
console.error(`Failed to load schema: ${schemaPath}`);
console.error(err.message);
process.exit(1);
}
}
/**
* Extract frontmatter from agent file
*/
function extractFrontmatter(content) {
const match = content.match(/^---\n([\s\S]*?)\n---/);
if (!match) {
return null;
}
try {
return load(match[1]);
} catch (err) {
return { error: `Failed to parse YAML: ${err.message}` };
}
}
/**
* Validate agent file
*/
function validateAgent(filePath) {
const fileName = path.basename(filePath);
const agentName = fileName.replace(/\.agent\.md$/, '').replace(/\.md$/, '');
results.total++;
// Read file
let content;
try {
content = fs.readFileSync(filePath, 'utf-8');
} catch (err) {
results.invalid++;
results.errors.push(`[${agentName}] Cannot read file: ${err.message}`);
results.agents[agentName] = { valid: false, errors: [err.message] };
return;
}
// Extract frontmatter
const frontmatter = extractFrontmatter(content);
if (!frontmatter) {
results.invalid++;
results.errors.push(`[${agentName}] No frontmatter found`);
results.agents[agentName] = {
valid: false,
errors: ['No frontmatter found'],
};
return;
}
if (frontmatter.error) {
results.invalid++;
results.errors.push(`[${agentName}] ${frontmatter.error}`);
results.agents[agentName] = { valid: false, errors: [frontmatter.error] };
return;
}
if (frontmatter.file_type && frontmatter.file_type !== 'agent') {
results.skipped++;
results.agents[agentName] = {
valid: true,
skipped: true,
frontmatter,
errors: [],
warnings: [`Skipped file_type=${frontmatter.file_type}`],
};
return;
}
// Validate against schema
const schema = loadSchema(path.join(SCHEMAS_DIR, 'frontmatter.schema.json'));
const validate = ajv.compile(schema);
const valid = validate(frontmatter);
const agentResult = {
valid,
frontmatter,
errors: [],
warnings: [],
};
if (!valid) {
results.invalid++;
agentResult.errors = validate.errors.map((e) => `${e.dataPath || 'root'}: ${e.message}`);
results.errors.push(
`[${agentName}] Schema validation failed: ${agentResult.errors.join('; ')}`
);
} else {
results.valid++;
}
// Additional validations
validateTools(agentName, frontmatter, agentResult);
validateHandoffs(agentName, frontmatter, agentResult);
if (agentResult.warnings.length > 0) {
results.warnings += agentResult.warnings.length;
}
results.agents[agentName] = agentResult;
}
/**
* Validate tools
*/
function validateTools(agentName, frontmatter, result) {
if (!frontmatter.tools) {
result.warnings.push('No tools specified (will default to all available)');
return;
}
const validTools = [
'shell',
'bash',
'powershell',
'read',
'edit',
'write',
'search',
'grep',
'glob',
'custom-agent',
'task',
'web',
'websearch',
'webfetch',
'todo',
'todowrite',
];
if (typeof frontmatter.tools === 'string') {
if (frontmatter.tools !== '*') {
result.warnings.push(`Invalid tool string: ${frontmatter.tools}`);
}
} else if (Array.isArray(frontmatter.tools)) {
for (const tool of frontmatter.tools) {
if (!validTools.includes(tool) && !tool.includes('/') && tool !== '*') {
result.warnings.push(`Unknown tool: ${tool}`);
}
}
}
}
/**
* Validate handoffs
*/
function validateHandoffs(agentName, frontmatter, result) {
if (!frontmatter.handoffs || !Array.isArray(frontmatter.handoffs)) {
return;
}
for (const handoff of frontmatter.handoffs) {
if (!handoff.agent) {
result.errors.push('Handoff missing agent name');
continue;
}
// Check for circular dependencies
if (handoff.agent === agentName) {
result.errors.push(`Circular handoff: ${agentName} hands off to itself`);
}
// Verify target agent exists
const agentFile = findAgentFileByName(handoff.agent);
if (!agentFile) {
result.warnings.push(`Handoff target not found: ${handoff.agent}`);
}
}
}
/**
* Find an agent file by base agent name across active agent directories.
*/
function findAgentFileByName(agentName) {
for (const dir of AGENT_DIRS) {
const agentFile = path.join(dir, `${agentName}.agent.md`);
if (fs.existsSync(agentFile)) {
return agentFile;
}
}
return null;
}
/**
* Find all agent files
*/
function findAgentFiles() {
if (targetAgent) {
const agentFile = findAgentFileByName(targetAgent);
if (!agentFile) {
console.error(`Agent not found: ${targetAgent}`);
process.exit(1);
}
return [agentFile];
}
return AGENT_DIRS.flatMap((dir) => globSync(path.join(dir, '*.agent.md')));
}
/**
* Generate report
*/
function generateReport() {
if (outputJson) {
console.log(JSON.stringify(results, null, 2));
if (results.invalid > 0) {
process.exit(1);
}
return;
}
console.log('\n╔════════════════════════════════════════════════════════════╗');
console.log('║ Agent Frontmatter Validation Report ║');
console.log('╚════════════════════════════════════════════════════════════╝\n');
console.log(`Total agents: ${results.total}`);
console.log(`Valid: ${results.valid} ✓`);
console.log(`Invalid: ${results.invalid} ✗`);
console.log(`Skipped: ${results.skipped}`);
console.log(`Warnings: ${results.warnings} ⚠`);
if (results.errors.length > 0) {
console.log('\n📋 ERRORS:\n');
results.errors.forEach((err) => console.log(` • ${err}`));
}
if (!outputJson) {
console.log('\n📊 AGENT DETAILS:\n');
for (const [agentName, agentResult] of Object.entries(results.agents)) {
const status = agentResult.valid ? '✓ VALID' : '✗ INVALID';
console.log(` ${agentName}: ${status}`);
if (verbose && agentResult.errors.length > 0) {
agentResult.errors.forEach((err) => console.log(` • ${err}`));
}
if (verbose && agentResult.warnings.length > 0) {
agentResult.warnings.forEach((warn) => console.log(` ⚠ ${warn}`));
}
}
}
console.log('\n');
// Exit with appropriate code
if (results.invalid > 0) {
process.exit(1);
}
}
/**
* Main execution
*/
function main() {
if (verbose) {
console.log(`Validating agents in: ${AGENT_DIRS.join(', ')}\n`);
}
const agentFiles = findAgentFiles();
if (agentFiles.length === 0) {
console.error('No agent files found');
process.exit(1);
}
for (const file of agentFiles) {
validateAgent(file);
}
generateReport();
}
main();