-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrules-sync.mjs
More file actions
439 lines (393 loc) · 15.2 KB
/
Copy pathrules-sync.mjs
File metadata and controls
439 lines (393 loc) · 15.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
/**
* rules-sync.mjs — #191
* Syncs canonical rules from the plugin's rules/ library into a consumer repo's .claude/rules/.
*
* Stdlib-only, cross-platform, no Zod, no third-party parsers. ESM module.
* Preserves local rules (files without the plugin source header).
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, basename, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { validateRuleContent } from './validate-vendored-rules.mjs';
// Exported (issue #722 Epic A Wave 2) for external consumers (e.g. tests).
// NOT imported by validate-vendored-rules.mjs — that module imports
// validateRuleContent FROM this file (see the pre-write gate below), so
// importing this constant back would create a module-load cycle; it keeps
// its own textually-identical copy instead.
export const PLUGIN_HEADER_PREFIX = '<!-- source: session-orchestrator plugin';
/**
* Parses the _index.md file and returns an array of entries for each
* requested category. Each entry's `relPath` is relative to pluginRoot.
*
* Supports the optional trailing `[archetypes: a, b]` tag (issue #722 Epic A
* Wave 3) on a bullet line:
*
* - `opt-in-stack/foo.md` — description [archetypes: nextjs-minimal, node-minimal]
*
* A bullet without the tag resolves to `archetypes: null` (universal —
* vendored to every consumer repo, matching pre-Wave-3 behavior exactly).
* Archetype values are lower-cased at parse time so downstream comparison is
* always case-insensitive.
*
* @param {string} indexContent - raw content of rules/_index.md
* @param {string[]} categories - e.g. ['always-on']
* @returns {Array<{relPath: string, archetypes: string[]|null}>} entries like
* { relPath: 'rules/always-on/parallel-sessions.md', archetypes: null }
*/
function parseIndex(indexContent, categories) {
const entries = [];
for (const category of categories) {
// Match the section header for this category
const sectionRe = new RegExp(`^##\\s+${escapeRegex(category)}[^\\n]*$`, 'm');
const sectionMatch = sectionRe.exec(indexContent);
if (!sectionMatch) continue;
const sectionStart = sectionMatch.index + sectionMatch[0].length;
// Everything until the next ## heading (or end of file)
const nextSectionMatch = /^##\s+/m.exec(indexContent.slice(sectionStart));
const sectionEnd =
nextSectionMatch !== null
? sectionStart + nextSectionMatch.index
: indexContent.length;
const sectionBody = indexContent.slice(sectionStart, sectionEnd);
// Extract bullet items: - `always-on/some-file.md` — description [archetypes: a, b]
const bulletRe = /^-\s+`([^`]+\.md)`([^\n]*)$/gm;
let match;
while ((match = bulletRe.exec(sectionBody)) !== null) {
const relPath = `rules/${match[1]}`;
const rest = match[2] ?? '';
const archetypeMatch = /\[archetypes:\s*([^\]]+)\]/i.exec(rest);
const archetypes = archetypeMatch
? archetypeMatch[1]
.split(',')
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
: null;
entries.push({ relPath, archetypes });
}
}
return entries;
}
function listManifestCategories(indexContent) {
const categories = [];
const headingRe = /^##\s+([^\n]+)$/gm;
let headingMatch;
while ((headingMatch = headingRe.exec(indexContent)) !== null) {
const headingText = headingMatch[1].trim();
const category = headingText.split(/\s+/)[0];
const sectionStart = headingMatch.index + headingMatch[0].length;
const nextSectionMatch = /^##\s+/m.exec(indexContent.slice(sectionStart));
const sectionEnd =
nextSectionMatch !== null
? sectionStart + nextSectionMatch.index
: indexContent.length;
const sectionBody = indexContent.slice(sectionStart, sectionEnd);
const bulletRe = /^-\s+`([^`]+\.md)`/gm;
let bulletMatch;
while ((bulletMatch = bulletRe.exec(sectionBody)) !== null) {
const rel = bulletMatch[1];
if (rel.includes('<')) continue;
categories.push(category);
break;
}
}
return categories;
}
/**
* Resolves the target repo's archetype (issue #722 Epic A Wave 3).
*
* Precedence: explicit `archetype` argument (CLI `--archetype` / caller
* override) beats `.orchestrator/bootstrap.lock` resolution. When neither is
* available, or the lock file's `archetype:` value is absent/`null`, the
* archetype is "unknown" — archetype-scoped entries are skipped, universal
* entries still vendor.
*
* @param {string} repoRoot
* @param {string|null} explicitArchetype
* @returns {{archetype: string|null, known: boolean}}
*/
function resolveArchetype(repoRoot, explicitArchetype) {
if (explicitArchetype) {
return { archetype: explicitArchetype.trim().toLowerCase(), known: true };
}
const lockPath = join(repoRoot, '.orchestrator', 'bootstrap.lock');
if (!existsSync(lockPath)) {
return { archetype: null, known: false };
}
let lockContent;
try {
lockContent = readFileSync(lockPath, 'utf8');
} catch {
return { archetype: null, known: false };
}
const m = /^archetype:\s*(.+?)\s*$/m.exec(lockContent);
if (!m) return { archetype: null, known: false };
let value = m[1].replace(/\s+#.*$/, '').trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1).trim();
}
if (!value || value.toLowerCase() === 'null') {
return { archetype: null, known: false };
}
return { archetype: value.toLowerCase(), known: true };
}
/**
* Escapes a string for use in a RegExp.
* @param {string} s
* @returns {string}
*/
function escapeRegex(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Syncs canonical rules from the plugin's rules/ library into a consumer repo.
*
* When `validate` is true (the default — issue #722 Epic A Wave 2),
* validateRuleContent() runs as a pre-write gate on every source file before
* it is copied. A file with any error-severity violation (paths-frontmatter,
* missing provenance header, unfilled placeholder) is recorded in `errors[]`
* and its write is skipped entirely — it is never added to
* written/skipped/preserved. Warn-severity violations (zero-match-globs,
* foreign-glob) do NOT block the write; they are collected into the
* additive `warnings[]` array instead. `requireProvenance` (default `true`)
* is forwarded to that gate call — pass `false` only for test fixtures that
* intentionally exercise unprovenanced content.
*
* Archetype filtering (issue #722 Epic A Wave 3): an `_index.md` entry may
* carry a trailing `[archetypes: a, b]` tag (see `rules/_index.md` § Entry
* syntax). When present, the entry is vendored ONLY when it matches the
* target repo's resolved archetype — explicit `archetype` argument first,
* falling back to `<repoRoot>/.orchestrator/bootstrap.lock`'s `archetype:`
* line. A mismatch is recorded in `skipped[]` as
* `{ file, reason: 'archetype-mismatch' }`; an unresolvable target archetype
* is recorded as `{ file, reason: 'archetype-unknown' }`. Untagged
* (universal) entries always vendor, unaffected by archetype resolution —
* this preserves full backward compatibility with pre-Wave-3 `_index.md`
* files and callers that never pass `archetype`.
*
* When `categories` is null/omitted, sync every `_index.md` category that has
* at least one concrete bullet entry. This keeps `/bootstrap --sync-rules`
* ready for future opt-in categories without requiring CLI changes.
*
* @param {{
* pluginRoot: string,
* repoRoot: string,
* categories?: string[]|null,
* dryRun?: boolean,
* validate?: boolean,
* requireProvenance?: boolean,
* archetype?: string|null
* }} opts
* @returns {{
* written: string[],
* skipped: Array<string|{file: string, reason: string}>,
* preserved: string[],
* errors: Array<{file: string, reason: string}>,
* warnings: Array<{file: string, reason: string}>
* }}
*/
export function syncRules({
pluginRoot,
repoRoot,
categories = null,
dryRun = false,
validate = true,
requireProvenance = true,
archetype = null,
} = {}) {
const written = [];
const skipped = [];
const preserved = [];
const errors = [];
const warnings = [];
if (!pluginRoot || typeof pluginRoot !== 'string') {
errors.push({ file: '_index.md', reason: 'pluginRoot not provided' });
return { written, skipped, preserved, errors, warnings };
}
if (!repoRoot || typeof repoRoot !== 'string') {
errors.push({ file: '_index.md', reason: 'repoRoot not provided' });
return { written, skipped, preserved, errors, warnings };
}
const indexPath = join(pluginRoot, 'rules', '_index.md');
if (!existsSync(indexPath)) {
errors.push({ file: '_index.md', reason: `_index.md not found at ${indexPath}` });
return { written, skipped, preserved, errors, warnings };
}
let indexContent;
try {
indexContent = readFileSync(indexPath, 'utf8');
} catch (err) {
errors.push({ file: '_index.md', reason: `failed to read _index.md: ${err.message}` });
return { written, skipped, preserved, errors, warnings };
}
const selectedCategories = Array.isArray(categories)
? categories
: listManifestCategories(indexContent);
const entries = parseIndex(indexContent, selectedCategories);
if (entries.length === 0) {
// No sources resolved — could be empty categories or malformed index
for (const cat of selectedCategories.length > 0 ? selectedCategories : ['<none>']) {
errors.push({
file: `rules/${cat}/*.md`,
reason: `no sources resolved for category '${cat}' in _index.md`,
});
}
return { written, skipped, preserved, errors, warnings };
}
const targetDir = join(repoRoot, '.claude', 'rules');
const resolvedArchetype = resolveArchetype(repoRoot, archetype);
const targetBasenames = new Map();
for (const entry of entries) {
const { relPath, archetypes } = entry;
// Archetype filter (issue #722 Epic A Wave 3) — evaluated before any
// file IO, so a skip never triggers a spurious "source file not found".
if (archetypes !== null) {
if (!resolvedArchetype.known) {
skipped.push({ file: relPath, reason: 'archetype-unknown' });
continue;
}
if (!archetypes.includes(resolvedArchetype.archetype)) {
skipped.push({ file: relPath, reason: 'archetype-mismatch' });
continue;
}
}
const srcPath = join(pluginRoot, relPath);
const fileName = basename(relPath);
const targetPath = join(targetDir, fileName);
if (targetBasenames.has(fileName)) {
errors.push({
file: relPath,
reason: `duplicate target filename '${fileName}' also used by ${targetBasenames.get(fileName)}`,
});
continue;
}
targetBasenames.set(fileName, relPath);
if (!existsSync(srcPath)) {
errors.push({ file: relPath, reason: `source file not found: ${srcPath}` });
continue;
}
let srcContent;
try {
srcContent = readFileSync(srcPath, 'utf8');
} catch (err) {
errors.push({ file: relPath, reason: `failed to read source: ${err.message}` });
continue;
}
// Pre-write validation gate (issue #722 Epic A Wave 2). Runs BEFORE the
// existsSync(targetPath) write-decision branch below, so a validation
// failure skips the write regardless of whether the target already
// exists, is stale, or is missing.
if (validate) {
const validation = validateRuleContent({
content: srcContent,
relPath,
requireProvenance,
targetRoot: repoRoot,
});
const errorViolations = validation.violations.filter((v) => v.severity === 'error');
if (errorViolations.length > 0) {
errors.push({
file: relPath,
reason: `validation-failed: ${errorViolations.map((v) => v.rule).join(', ')}`,
});
continue;
}
const warnViolations = validation.violations.filter((v) => v.severity === 'warn');
for (const v of warnViolations) {
warnings.push({ file: relPath, reason: `${v.rule}: ${v.message}` });
}
}
if (existsSync(targetPath)) {
let targetContent;
try {
targetContent = readFileSync(targetPath, 'utf8');
} catch (err) {
errors.push({ file: targetPath, reason: `failed to read target: ${err.message}` });
continue;
}
const firstLine = targetContent.split('\n')[0] ?? '';
if (!firstLine.startsWith(PLUGIN_HEADER_PREFIX)) {
// Local file — preserve it
preserved.push(fileName);
continue;
}
if (targetContent === srcContent) {
// Already up to date
skipped.push(fileName);
continue;
}
// Plugin-owned file with stale content — overwrite
if (!dryRun) {
try {
writeFileSync(targetPath, srcContent, 'utf8');
} catch (err) {
errors.push({ file: targetPath, reason: `failed to write: ${err.message}` });
continue;
}
}
written.push(fileName);
} else {
// Target does not exist — write it
if (!dryRun) {
try {
mkdirSync(targetDir, { recursive: true });
writeFileSync(targetPath, srcContent, 'utf8');
} catch (err) {
errors.push({ file: targetPath, reason: `failed to write: ${err.message}` });
continue;
}
}
written.push(fileName);
}
}
return { written, skipped, preserved, errors, warnings };
}
// ── CLI ───────────────────────────────────────────────────────────────────────
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Detect direct execution: node scripts/lib/rules-sync.mjs
const isMain =
typeof process !== 'undefined' &&
process.argv[1] !== null &&
process.argv[1] !== undefined &&
resolve(process.argv[1]) === resolve(__filename);
if (isMain) {
const args = process.argv.slice(2);
function getArg(name) {
const idx = args.indexOf(name);
return idx !== -1 ? args[idx + 1] : undefined;
}
function getAllArgs(name) {
const values = [];
for (let i = 0; i < args.length; i++) {
if (args[i] === name && args[i + 1]) values.push(args[i + 1]);
}
return values;
}
const repoRoot = getArg('--repo-root');
const dryRun = args.includes('--dry-run');
// Explicit archetype override (issue #722 Epic A Wave 3) — beats
// .orchestrator/bootstrap.lock resolution inside syncRules().
const archetype = getArg('--archetype') ?? null;
const categoryArgs = [
...getAllArgs('--category'),
...(getArg('--categories') ?? '').split(','),
]
.map((s) => s.trim())
.filter(Boolean);
const categories = categoryArgs.length > 0 ? categoryArgs : null;
if (!repoRoot) {
process.stderr.write('rules-sync: error: --repo-root <path> is required\n');
process.exit(1);
}
// Plugin root is two directories up from scripts/lib/
const pluginRoot = resolve(__dirname, '..', '..');
const result = syncRules({ pluginRoot, repoRoot, dryRun, archetype, categories });
process.stdout.write(JSON.stringify(result, null, 2) + '\n');
if (result.errors.length > 0) {
process.exit(1);
}
process.exit(0);
}