Repository navigation
Expand file tree
/
Copy pathgenerate-agent-index.js
More file actions
401 lines (336 loc) · 12.5 KB
/
Copy pathgenerate-agent-index.js
File metadata and controls
401 lines (336 loc) · 12.5 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
#!/usr/bin/env node
/**
* Agent Index Generator
* Generates searchable agent index from all .agent.md specification files
* Outputs to docs/AGENT-INDEX.md
*/
import fs from "fs";
import path from "path";
import * as YAML from "js-yaml";
import { fileURLToPath, pathToFileURL } from "url";
import { isRootRelativeImplementation } from "./implementation-path.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const REPO_ROOT = path.join(__dirname, "../../");
const OUTPUT_FILE = path.join(__dirname, "../../docs/AGENT-INDEX.md");
const AGENT_LOCATIONS = [
path.join(REPO_ROOT, "agents"),
path.join(REPO_ROOT, ".github/agents"),
];
// Category metadata
const CATEGORY_INFO = {
configuration: { icon: "⚙️", description: "Configuration and setup agents" },
analysis: { icon: "🔍", description: "Analysis and research agents" },
integration: { icon: "🔗", description: "Integration and API agents" },
planning: { icon: "📋", description: "Planning and roadmap agents" },
governance: { icon: "📋", description: "Governance and process agents" },
automation: { icon: "⚡", description: "Automation and workflow agents" },
tooling: { icon: "🛠️", description: "Development tools and utilities" },
mode: { icon: "🎯", description: "Operational modes and frameworks" },
};
// Parse YAML frontmatter
function parseFrontmatter(content) {
const match = content.match(/^---\n([\s\S]*?)\n---/);
if (!match) return null;
try {
return YAML.load(match[1]);
} catch (error) {
console.error(`Error parsing frontmatter: ${error.message}`);
return null;
}
}
// Parse agent spec file
function parseAgentSpec(filePath, repoRoot) {
try {
const content = fs.readFileSync(filePath, "utf8");
const frontmatter = parseFrontmatter(content);
if (!frontmatter) {
console.warn(`Invalid frontmatter in ${filePath}`);
return null;
}
// Extract first paragraph of content after frontmatter
const contentMatch = content.match(
/^---\n[\s\S]*?\n---\n+([\s\S]*?)(?:\n##|$)/,
);
const summary = contentMatch ? contentMatch[1].trim().split("\n")[0] : "";
// Calculate relative path from repo root for correct linking
const relPath = path.relative(repoRoot, filePath);
return {
name: frontmatter.name || path.basename(filePath, ".agent.md"),
description: frontmatter.description || summary || "",
file: path.basename(filePath),
path: relPath,
category: frontmatter.category || "unknown",
status: frontmatter.status || "active",
version: frontmatter.version || "1.0.0",
implementation: frontmatter.implementation || null,
tags: frontmatter.tags || [],
created_date: frontmatter.created_date || "",
last_updated: frontmatter.last_updated || "",
author: frontmatter.author || "Unknown",
language: frontmatter.language || "en",
};
} catch (error) {
console.error(`Error parsing ${filePath}: ${error.message}`);
return null;
}
}
// Collect all agent specs
function collectAgentSpecs() {
const specs = [];
// Find all .agent.md files
function walkDir(dir) {
if (!fs.existsSync(dir)) {
return;
}
try {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
walkDir(filePath);
} else if (file.endsWith(".agent.md")) {
const spec = parseAgentSpec(filePath, REPO_ROOT);
if (spec) {
specs.push(spec);
}
}
}
} catch (error) {
console.warn(`Error reading directory ${dir}: ${error.message}`);
}
}
// Search all agent locations
for (const location of AGENT_LOCATIONS) {
walkDir(location);
}
// Also search plugins directories (handle glob-like pattern)
const pluginsDir = path.join(REPO_ROOT, "plugins");
if (fs.existsSync(pluginsDir)) {
const pluginDirs = fs.readdirSync(pluginsDir);
for (const pluginDir of pluginDirs) {
const agentsPath = path.join(pluginsDir, pluginDir, "agents");
walkDir(agentsPath);
}
}
return specs.sort((a, b) => a.name.localeCompare(b.name));
}
// Build the implementation link for the Discovery section.
//
// `spec.path` and repo-root-relative `spec.implementation` values (anything
// containing a `/`, e.g. `agents/changelog-agent/`) are both relative to the
// repository root, so joining the implementation onto the spec's directory
// double-prefixes the path (`agents/agents/...`). Only bare names keep the
// legacy spec-directory-relative join.
function buildImplementationLink(spec) {
const raw = String(spec.implementation);
// The result is a link target, not a filesystem path, so use POSIX
// operations and forward slashes on every platform (`spec.path` comes from
// `path.relative`, which emits backslashes on Windows).
// The root-relative rule is shared with the validator (implementation-path.js).
// A bare name keeps this generator's legacy meaning: relative to the spec's folder.
const specDir = path.posix.dirname(spec.path.split(path.sep).join("/"));
const joined = isRootRelativeImplementation(raw)
? path.posix.normalize(raw)
: path.posix.join(specDir, raw);
// path.normalize keeps one trailing slash; strip it so the template below
// emits exactly one. (`agents/X/` must not become `agents/X//`.)
const implPath = joined.replace(/\/+$/, "");
const display = raw.endsWith("/") ? raw : `${raw}/`;
return `[\`${display}\`](../${implPath}/)`;
}
// Generate markdown index
function generateIndex(specs) {
const today = new Date().toISOString().split("T")[0];
let markdown = `---
file_type: documentation
title: Agent Index
description: Searchable index of all agent specifications
created_date: ${today}
last_updated: ${today}
author: Agent Index Generator
language: en
status: active
---
# Agent Index
Complete searchable index of all ${specs.length} agent specifications in the LightSpeed \`.github\` control plane.
**Generated**: ${today}
## Quick Stats
| Metric | Count |
| --- | --- |
| Total Agents | ${specs.length} |
| Active Agents | ${specs.filter((s) => s.status === "active").length} |
| Draft Agents | ${specs.filter((s) => s.status === "draft").length} |
| Deprecated Agents | ${specs.filter((s) => s.status === "deprecated").length} |
## Agents by Category
`;
// Group by category
const byCategory = {};
for (const spec of specs) {
const cat = spec.category || "unknown";
if (!byCategory[cat]) {
byCategory[cat] = [];
}
byCategory[cat].push(spec);
}
// Generate category sections
for (const [category, agents] of Object.entries(byCategory)) {
const catInfo = CATEGORY_INFO[category] || {
icon: "📦",
description: category,
};
markdown += `\n### ${catInfo.icon} ${category.charAt(0).toUpperCase() + category.slice(1)}\n\n`;
markdown += `${catInfo.description}\n\n`;
markdown += `| Agent | Status | Version | Tags |\n`;
markdown += `| --- | --- | --- | --- |\n`;
for (const agent of agents) {
const statusBadge =
agent.status === "active"
? "✅ Active"
: agent.status === "draft"
? "📝 Draft"
: "🚫 Deprecated";
const tags =
agent.tags.length > 0
? agent.tags.map((t) => `\`${t}\``).join(", ")
: "—";
const specLink = `[${agent.name}](../${agent.path})`;
markdown += `| ${specLink} | ${statusBadge} | ${agent.version} | ${tags} |\n`;
}
markdown += "\n";
}
// Add all agents section
markdown += `\n## All Agents (Alphabetical)\n\n`;
markdown += `| Agent | Category | Status | Version | Updated |\n`;
markdown += `| --- | --- | --- | --- | --- |\n`;
for (const spec of specs) {
const statusBadge =
spec.status === "active" ? "✅" : spec.status === "draft" ? "📝" : "🚫";
const specLink = `[${spec.name}](../${spec.path})`;
const catInfo = CATEGORY_INFO[spec.category] || { icon: "📦" };
markdown += `| ${specLink} | ${catInfo.icon} ${spec.category} | ${statusBadge} ${spec.status} | ${spec.version} | ${spec.last_updated} |\n`;
}
// Add discovery section
markdown += `\n## Discovery\n\n`;
markdown += `### By Implementation Status\n\n`;
markdown += `**With Implementation Directory** (${specs.filter((s) => s.implementation).length})\n\n`;
for (const spec of specs.filter((s) => s.implementation)) {
markdown += `- [${spec.name}](../${spec.path}) → ${buildImplementationLink(spec)}\n`;
}
markdown += `\n**Specification-Only** (${specs.filter((s) => !s.implementation).length})\n\n`;
for (const spec of specs.filter((s) => !s.implementation)) {
markdown += `- [${spec.name}](../${spec.path}) — ${spec.description}\n`;
}
// Add tags section
const allTags = new Set();
for (const spec of specs) {
for (const tag of spec.tags) {
allTags.add(tag);
}
}
if (allTags.size > 0) {
markdown += `\n## Agents by Tag\n\n`;
for (const tag of Array.from(allTags).sort()) {
const tagged = specs.filter((s) => s.tags.includes(tag));
markdown += `### \`${tag}\`\n\n`;
for (const spec of tagged) {
markdown += `- [${spec.name}](../${spec.path})\n`;
}
markdown += "\n";
}
}
// Add author section
const byAuthor = {};
for (const spec of specs) {
const author = spec.author || "Unknown";
if (!byAuthor[author]) {
byAuthor[author] = [];
}
byAuthor[author].push(spec);
}
markdown += `\n## Agents by Author\n\n`;
for (const [author, agents] of Object.entries(byAuthor).sort()) {
markdown += `### ${author} (${agents.length})\n\n`;
for (const agent of agents) {
markdown += `- [${agent.name}](../${agent.path}) — ${agent.description}\n`;
}
markdown += "\n";
}
// Add footer
markdown += `\n---\n\n`;
markdown += `## Related Documentation\n\n`;
markdown += `- [Agent Developer Guide](./AGENT-DEVELOPER-GUIDE.md)\n`;
markdown += `- [Agent Specification Audit - Phase 3 Results](../.github/reports/audit/AGENT-SPECS-PHASE3-RESULTS.md)\n`;
markdown += `- [CONTRIBUTING.md](../CONTRIBUTING.md)\n\n`;
markdown += `**Generated**: ${new Date().toISOString()}\n`;
markdown += `**Total Agents**: ${specs.length}\n`;
return markdown;
}
// Lines that legitimately change on every run (timestamps). The --check mode
// and the idempotency test ignore exactly these lines; everything else must
// be byte-identical between runs.
const STAMP_PATTERNS = [
/^(created_date|last_updated):/,
/^\*\*Generated\*\*:/,
/^Complete searchable index/,
];
function stripStamps(markdown) {
return markdown
.split("\n")
.filter((line) => !STAMP_PATTERNS.some((re) => re.test(line)))
.join("\n");
}
// Main execution
function main() {
const check = process.argv.includes("--check");
console.log("Generating agent index...");
const specs = collectAgentSpecs();
console.log(`Found ${specs.length} agent specifications`);
const markdown = generateIndex(specs);
if (check) {
const current = fs.existsSync(OUTPUT_FILE)
? fs.readFileSync(OUTPUT_FILE, "utf8")
: null;
if (current === null || stripStamps(current) !== stripStamps(markdown)) {
console.error("agent index drifted from generated output");
process.exit(1);
}
console.log("✅ Agent index is current (ignoring date stamps).");
return 0;
}
// Ensure directory exists
const outputDir = path.dirname(OUTPUT_FILE);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Write output
fs.writeFileSync(OUTPUT_FILE, markdown, "utf8");
console.log(`✅ Agent index generated: ${OUTPUT_FILE}`);
// Print summary
console.log("\n📊 Agent Index Summary:");
console.log(` Total agents: ${specs.length}`);
console.log(
` Active: ${specs.filter((s) => s.status === "active").length}`,
);
console.log(` Draft: ${specs.filter((s) => s.status === "draft").length}`);
console.log(
` Deprecated: ${specs.filter((s) => s.status === "deprecated").length}`,
);
const categories = {};
for (const spec of specs) {
categories[spec.category] = (categories[spec.category] || 0) + 1;
}
console.log("\n📂 By Category:");
for (const [cat, count] of Object.entries(categories).sort()) {
console.log(` ${cat}: ${count}`);
}
return 0;
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
process.exit(main());
}
export { buildImplementationLink, parseAgentSpec, generateIndex };