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
|
#!/usr/bin/env node
/**
* Build script to compile individual rule files into AGENTS.md
*/
import { readdir, readFile, writeFile } from 'fs/promises'
import { join } from 'path'
import { Rule, Section, GuidelinesDocument, ImpactLevel } from './types.js'
import { parseRuleFile, RuleFile } from './parser.js'
import { SKILLS, SkillConfig, DEFAULT_SKILL } from './config.js'
// Parse command line arguments
const args = process.argv.slice(2)
const upgradeVersion = args.includes('--upgrade-version')
const skillArg = args.find((arg) => arg.startsWith('--skill='))
const skillName = skillArg ? skillArg.split('=')[1] : null
const buildAll = args.includes('--all')
/**
* Increment a semver-style version string (e.g., "0.1.0" -> "0.1.1", "1.0" -> "1.1")
*/
function incrementVersion(version: string): string {
const parts = version.split('.').map(Number)
// Increment the last part
parts[parts.length - 1]++
return parts.join('.')
}
/**
* Generate markdown from rules
*/
function generateMarkdown(
sections: Section[],
metadata: {
version: string
organization: string
date: string
abstract: string
references?: string[]
},
skillConfig: SkillConfig
): string {
let md = `# ${skillConfig.title}\n\n`
md += `**Version ${metadata.version}** \n`
md += `${metadata.organization} \n`
md += `${metadata.date}\n\n`
md += `> **Note:** \n`
md += `> This document is mainly for agents and LLMs to follow when maintaining, \n`
md += `> generating, or refactoring ${skillConfig.description}. Humans \n`
md += `> may also find it useful, but guidance here is optimized for automation \n`
md += `> and consistency by AI-assisted workflows.\n\n`
md += `---\n\n`
md += `## Abstract\n\n`
md += `${metadata.abstract}\n\n`
md += `---\n\n`
md += `## Table of Contents\n\n`
// Generate TOC
sections.forEach((section) => {
md += `${section.number}. [${section.title}](#${
section.number
}-${section.title.toLowerCase().replace(/\s+/g, '-')}) — **${
section.impact
}**\n`
section.rules.forEach((rule) => {
// GitHub generates anchors from the full heading text: "1.1 Title" -> "#11-title"
const anchor = `${rule.id} ${rule.title}`
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]/g, '') // Remove special characters except hyphens
md += ` - ${rule.id} [${rule.title}](#${anchor})\n`
})
})
md += `\n---\n\n`
// Generate sections
sections.forEach((section) => {
md += `## ${section.number}. ${section.title}\n\n`
md += `**Impact: ${section.impact}${
section.impactDescription ? ` (${section.impactDescription})` : ''
}**\n\n`
if (section.introduction) {
md += `${section.introduction}\n\n`
}
section.rules.forEach((rule) => {
md += `### ${rule.id} ${rule.title}\n\n`
md += `**Impact: ${rule.impact}${
rule.impactDescription ? ` (${rule.impactDescription})` : ''
}**\n\n`
md += `${rule.explanation}\n\n`
rule.examples.forEach((example) => {
if (example.description) {
md += `**${example.label}: ${example.description}**\n\n`
} else {
md += `**${example.label}:**\n\n`
}
// Only generate code block if there's actual code
if (example.code && example.code.trim()) {
md += `\`\`\`${example.language || 'typescript'}\n`
md += `${example.code}\n`
md += `\`\`\`\n\n`
}
if (example.additionalText) {
md += `${example.additionalText}\n\n`
}
})
if (rule.references && rule.references.length > 0) {
md += `Reference: ${rule.references
.map((ref) => `[${ref}](${ref})`)
.join(', ')}\n\n`
}
})
md += `---\n\n`
})
// Add references section
if (metadata.references && metadata.references.length > 0) {
md += `## References\n\n`
metadata.references.forEach((ref, i) => {
md += `${i + 1}. [${ref}](${ref})\n`
})
}
return md
}
/**
* Build a single skill
*/
async function buildSkill(skillConfig: SkillConfig) {
console.log(`\nBuilding ${skillConfig.name}...`)
console.log(` Rules directory: ${skillConfig.rulesDir}`)
console.log(` Output file: ${skillConfig.outputFile}`)
// Read all rule files (exclude files starting with _ and README.md)
const files = await readdir(skillConfig.rulesDir)
const ruleFiles = files
.filter((f) => f.endsWith('.md') && !f.startsWith('_') && f !== 'README.md')
.sort() // Sort filenames for consistent ordering across systems
const ruleData: RuleFile[] = []
for (const file of ruleFiles) {
const filePath = join(skillConfig.rulesDir, file)
try {
const parsed = await parseRuleFile(filePath, skillConfig.sectionMap)
ruleData.push(parsed)
} catch (error) {
console.error(` Error parsing ${file}:`, error)
}
}
// Group rules by section
const sectionsMap = new Map<number, Section>()
ruleData.forEach(({ section, rule }) => {
if (!sectionsMap.has(section)) {
sectionsMap.set(section, {
number: section,
title: `Section ${section}`, // Will be overridden by section metadata
impact: rule.impact,
rules: [],
})
}
sectionsMap.get(section)!.rules.push(rule)
})
// Sort rules within each section by title (using en-US locale for consistency across environments)
sectionsMap.forEach((section) => {
section.rules.sort((a, b) =>
a.title.localeCompare(b.title, 'en-US', { sensitivity: 'base' })
)
// Assign IDs based on sorted order
section.rules.forEach((rule, index) => {
rule.id = `${section.number}.${index + 1}`
rule.subsection = index + 1
})
})
// Convert to array and sort
const sections = Array.from(sectionsMap.values()).sort(
(a, b) => a.number - b.number
)
// Read section metadata from consolidated _sections.md file
const sectionsFile = join(skillConfig.rulesDir, '_sections.md')
try {
const sectionsContent = await readFile(sectionsFile, 'utf-8')
// Parse sections using regex to match each section block
const sectionBlocks = sectionsContent
.split(/(?=^## \d+\. )/m)
.filter(Boolean)
for (const block of sectionBlocks) {
// Extract section number and title, removing section ID in parentheses
const headerMatch = block.match(/^## (\d+)\.\s+(.+?)(?:\s+\([^)]+\))?$/m)
if (!headerMatch) continue
const sectionNumber = parseInt(headerMatch[1])
const sectionTitle = headerMatch[2].trim() // Strip (id) for output
// Extract impact (format: **Impact:** CRITICAL)
const impactMatch = block.match(/\*\*Impact:\*\*\s+(\w+(?:-\w+)?)/i)
const impactLevel = impactMatch
? (impactMatch[1].toUpperCase().replace(/-/g, '-') as ImpactLevel)
: 'MEDIUM'
// Extract description (format: **Description:** text)
const descMatch = block.match(/\*\*Description:\*\*\s+(.+?)(?=\n\n##|$)/s)
const description = descMatch ? descMatch[1].trim() : ''
// Update section if it exists
const section = sections.find((s) => s.number === sectionNumber)
if (section) {
section.title = sectionTitle
section.impact = impactLevel
section.introduction = description
}
}
} catch (error) {
console.warn(' Warning: Could not read _sections.md, using defaults')
}
// Read metadata
let metadata
try {
const metadataContent = await readFile(skillConfig.metadataFile, 'utf-8')
metadata = JSON.parse(metadataContent)
} catch {
metadata = {
version: '1.0.0',
organization: 'Engineering',
date: new Date().toLocaleDateString('en-US', {
month: 'long',
year: 'numeric',
}),
abstract: `Performance optimization guide for ${skillConfig.description}, ordered by impact.`,
}
}
// Upgrade version if flag is passed
if (upgradeVersion) {
const oldVersion = metadata.version
metadata.version = incrementVersion(oldVersion)
console.log(` Upgrading version: ${oldVersion} -> ${metadata.version}`)
// Write updated metadata.json
await writeFile(
skillConfig.metadataFile,
JSON.stringify(metadata, null, 2) + '\n',
'utf-8'
)
console.log(` ✓ Updated metadata.json`)
// Update SKILL.md frontmatter if it exists
const skillFile = join(skillConfig.skillDir, 'SKILL.md')
try {
const skillContent = await readFile(skillFile, 'utf-8')
const updatedSkillContent = skillContent.replace(
/^(---[\s\S]*?version:\s*)"[^"]*"([\s\S]*?---)$/m,
`$1"${metadata.version}"$2`
)
await writeFile(skillFile, updatedSkillContent, 'utf-8')
console.log(` ✓ Updated SKILL.md`)
} catch {
// SKILL.md doesn't exist, skip
}
}
// Generate markdown
const markdown = generateMarkdown(sections, metadata, skillConfig)
// Write output
await writeFile(skillConfig.outputFile, markdown, 'utf-8')
console.log(
` ✓ Built AGENTS.md with ${sections.length} sections and ${ruleData.length} rules`
)
}
/**
* Main build function
*/
async function build() {
try {
console.log('Building AGENTS.md from rules...')
if (buildAll) {
// Build all skills
for (const skill of Object.values(SKILLS)) {
await buildSkill(skill)
}
} else if (skillName) {
// Build specific skill
const skill = SKILLS[skillName]
if (!skill) {
console.error(`Unknown skill: ${skillName}`)
console.error(`Available skills: ${Object.keys(SKILLS).join(', ')}`)
process.exit(1)
}
await buildSkill(skill)
} else {
// Build default skill (backwards compatibility)
await buildSkill(SKILLS[DEFAULT_SKILL])
}
console.log('\n✓ Build complete')
} catch (error) {
console.error('Build failed:', error)
process.exit(1)
}
}
build()
|