import { createHash } from 'node:crypto'; import { promises as fs } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const sourceRelative = '.claude/skills/frontend-fidelity'; const targetRelative = '.agents/skills/frontend-fidelity'; const manifestName = '.sync-manifest.json'; const ignored = new Set(['__pycache__', '.DS_Store', 'Thumbs.db']); function fingerprint(buffer, name) { // Normalize text checkout endings, but retain every byte of image/font assets. const textAsset = /\.(md|py|txt|yaml|yml|json|js|mjs|css|html|svg)$/i.test( name, ); const content = textAsset ? buffer.toString('utf8').replace(/\r\n/g, '\n') : buffer; return createHash('sha256').update(content).digest('hex'); } async function rejectLinkedParents(root, relative) { let current = root; for (const segment of relative.split('/')) { current = path.join(current, segment); try { const info = await fs.lstat(current); if (info.isSymbolicLink() || !info.isDirectory()) { throw new Error(`Expected an ordinary directory: ${current}`); } } catch (error) { if (error.code === 'ENOENT') return; throw error; } } } async function readTree(root, { allowMissing = false, target = false } = {}) { const files = new Map(); async function walk(directory, relative = '') { let entries; try { entries = await fs.readdir(directory, { withFileTypes: true }); } catch (error) { if (allowMissing && relative === '' && error.code === 'ENOENT') return; throw error; } for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { if (ignored.has(entry.name)) continue; const name = relative ? `${relative}/${entry.name}` : entry.name; const fullPath = path.join(directory, entry.name); if (entry.isSymbolicLink()) throw new Error(`Linked skill entry: ${fullPath}`); if (entry.isDirectory()) await walk(fullPath, name); else if (entry.isFile()) { if (target && name === manifestName) continue; const content = await fs.readFile(fullPath); files.set(name, { content, hash: fingerprint(content, name) }); } else throw new Error(`Unsupported skill entry: ${fullPath}`); } } await walk(root); return files; } export async function syncSkill(root, { check = false } = {}) { root = await fs.realpath(root); await rejectLinkedParents(root, sourceRelative); await rejectLinkedParents(root, targetRelative); const source = path.join(root, sourceRelative); const target = path.join(root, targetRelative); const sourceFiles = await readTree(source); if (!sourceFiles.has('SKILL.md') || sourceFiles.has(manifestName)) { throw new Error('Source must contain SKILL.md and no sync manifest'); } const targetFiles = await readTree(target, { allowMissing: true, target: true, }); const manifestPath = path.join(target, manifestName); let manifest; try { const info = await fs.lstat(manifestPath); if (!info.isFile() || info.isSymbolicLink()) throw new Error('Invalid manifest file'); manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')); if ( manifest.version !== 1 || manifest.source !== sourceRelative || !manifest.files || typeof manifest.files !== 'object' || Array.isArray(manifest.files) || Object.values(manifest.files).some((hash) => !/^[a-f0-9]{64}$/.test(hash)) ) throw new Error('Invalid sync manifest'); } catch (error) { if (error.code !== 'ENOENT') throw error; } // Validate the entire target before writing anything; preserve independent edits. const conflicts = []; if (!manifest && targetFiles.size) conflicts.push('Target is not empty and has no manifest'); if (manifest) { for (const [name, file] of targetFiles) { if (!Object.hasOwn(manifest.files, name)) conflicts.push(`Unknown target file: ${name}`); else if (file.hash !== manifest.files[name]) conflicts.push(`Target changed independently: ${name}`); } for (const name of Object.keys(manifest.files)) { if (!targetFiles.has(name)) conflicts.push(`Managed target file missing: ${name}`); if (!sourceFiles.has(name)) conflicts.push(`Source removed a managed file: ${name}`); } } if (conflicts.length) throw new Error(conflicts.join('\n')); const changed = [...sourceFiles].filter( ([name, file]) => targetFiles.get(name)?.hash !== file.hash, ); if (check) { if (!manifest || changed.length) { throw new Error( `Skill copies are out of sync: ${changed.map(([name]) => name).join(', ') || 'missing manifest'}`, ); } return { status: 'PASS', files: sourceFiles.size, changed: 0 }; } for (const [name, file] of changed) { const destination = path.join(target, name); await fs.mkdir(path.dirname(destination), { recursive: true }); await fs.writeFile(destination, file.content); } if (changed.length || !manifest) { const nextManifest = { version: 1, source: sourceRelative, files: Object.fromEntries( [...sourceFiles].map(([name, file]) => [name, file.hash]), ), }; await fs.writeFile( manifestPath, `${JSON.stringify(nextManifest, null, 2)}\n`, 'utf8', ); } return { status: 'PASS', files: sourceFiles.size, changed: changed.length }; } const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); if (isMain) { try { const args = process.argv.slice(2); if (args.some((arg) => arg !== '--check') || args.length > 1) { throw new Error( 'Usage: node scripts/sync-frontend-fidelity.mjs [--check]', ); } const root = path.resolve( path.dirname(fileURLToPath(import.meta.url)), '..', ); console.log( JSON.stringify( await syncSkill(root, { check: args.includes('--check') }), ), ); } catch (error) { console.error(error.message); process.exitCode = 1; } }