Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

20.5 KB
Raw Blame
// Kiểm nội dung mục trong gói mẫu (THIET-KE gói mẫu §3.2, luật L6, L7, L10).
//   lintGuidance(md)    → {errors[], warnings[], frontmatter, text}   (text = bản đã chuẩn hoá NFC + \n)
//   lintEditStyle(md)   → {errors[], warnings[], preset, guide, text} (preset đã kẹp số vào khoảng an toàn)
//   lintWebp(buf)       → {errors[], width, height}
// Chạy thử trên mẫu gốc: node packs/lint.mjs   (143 guidance + 14 cách dựng phải 0 lỗi)
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SFX_NAMES } from '../engine/audio/sfx.mjs';
import { MUSIC_STYLES } from '../engine/audio/music.mjs';

const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));

// ---------- giới hạn ----------
export const LIMITS = {
  template: { bytes: 16 * 1024, lines: 170, lineChars: 800 },
  style: { guideBytes: 8 * 1024, guideLines: 120, lineChars: 800, jsonBytes: 4 * 1024, jsonDepth: 4 },
  thumb: { bytes: 200 * 1024, maxW: 1080, maxH: 1920 },
};
export const FRONTMATTER_KEYS = ['id', 'title', 'category', 'genre', 'technique', 'difficulty', 'aspect', 'duration_s', 'narration'];
/** Khoá tuỳ chọn: 36 guidance gốc (109–144) có thêm `blurb` (mô tả ngắn cho catalog) ngoài 9 khoá của GUIDANCE-SPEC. */
export const FRONTMATTER_OPTIONAL = ['blurb'];
export const CATEGORIES = ['faceless', 'ads', 'multi-style', 'viet-nam'];
export const TECHNIQUES = ['svg', 'dom', 'canvas2d', 'webgl-shader', 'three'];
export const SECTIONS = ['1. Một câu', '2. Hợp với nội dung nào', '3. Ô nội dung', '4. Phong cách hình', '5. Bố cục', '6. Dòng thời gian',
  '7. Luật chuyển động', '8. Cách dựng bằng code', '9. Âm thanh (đề xuất)', '10. Khi nội dung dài hơn 8 giây', '11. Đừng làm', '12. Tự kiểm'];
export const STYLE_SECTIONS = ['Cắt', 'Phụ đề', 'Zoom', 'Đồ hoạ', 'Zoom và tiếng', 'Tiếng động', 'Nhạc', 'Tự kiểm'];
/** Kiểu chữ phụ đề có trong engine (khoá tra edit/captions-hf.mjs LOOKS) — cách dựng lạ chỉ được chọn 1 trong các kiểu này (tới khi xong V6). */
export const CAPTION_LOOKS = ['sach-gon', 'thong-tin-do-hoa', 'phu-de-nay-mau', 'podcast-trich-doan', 'ke-chuyen', 'top-danh-sach', 'review-san-pham',
  'huong-dan-buoc', 'ban-tin-nhanh', 'quan-diem-gat', 'chot-don-livestream', 'vlog-nhe', 'meo-15s', 'cau-noi-hay'];
export const LOOK_ENTERS = ['fade', 'fade-slow', 'pop', 'pop-soft', 'slam', 'slide-left', 'ticker', 'typewriter'];
export const GRAPHIC_TYPES = ['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card'];

/** Chữ cần đọc kỹ (cảnh báo, không chặn); UI tô vàng trong màn xem trước khi cài. */
export const WARN_WORDS = ['bỏ qua', 'ignore', 'system', 'prompt', 'instruction', 'Bash', 'tool', 'curl', 'fetch', 'eval', 'base64', 'token', 'key', 'password', 'mật khẩu', 'brief.json', 'notes'];

function fontFamilies() {
  try { return JSON.parse(fs.readFileSync(path.join(ROOT, 'engine', 'fonts', 'fonts.json'), 'utf8')).map((f) => f.family); } catch { return []; }
}

// ---------- chữ chung ----------
/** Chuẩn hoá + kiểm ký tự. Trả {text, errors}. */
export function normalizeText(input) {
  const errors = [];
  let s = input;
  if (Buffer.isBuffer(s)) {
    const dec = new TextDecoder('utf-8', { fatal: true });
    try { s = dec.decode(s); } catch { return { text: '', errors: ['không phải UTF-8'] }; }
  }
  if (typeof s !== 'string') return { text: '', errors: ['không phải chuỗi'] };
  if (s.charCodeAt(0) === 0xfeff) s = s.slice(1);
  s = s.replace(/\r\n/g, '\n').normalize('NFC');
  // eslint-disable-next-line no-control-regex
  const ctrl = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/.exec(s);
  if (ctrl) errors.push(`có ký tự điều khiển U+${ctrl[0].charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}`);
  const hidden = /[​-‏‪-‮⁠-⁩]|\uDB40[\uDC00-\uDC7F]/u.exec(s);
  if (hidden) errors.push(`có ký tự ẩn/đảo chiều U+${hidden[0].codePointAt(0).toString(16).toUpperCase()}`);
  return { text: s, errors };
}

/** Lỗi nội dung dùng chung cho guidance + phần hướng dẫn của cách dựng. */
function contentErrors(s) {
  const errors = [];
  if (/```/.test(s)) errors.push('có khối code ```');
  const url = /\b(?:https?|javascript|data|file|wss?|ftp|vbscript)\s*:/i.exec(s) || /(?:^|[\s("'=])\/\/[a-z0-9-]+(?:\.[a-z0-9-]+)+/im.exec(s) || /\bwww\.[a-z0-9-]+\.[a-z]/i.exec(s);
  if (url) errors.push(`có URL hoặc lược đồ: "${url[0].trim().slice(0, 40)}"`);
  const tag = /<\s*(?:script|iframe|img|svg|link|meta|object|embed|style|a\s|a>|base|form|input|video|audio|source|template)\b|<!--/i.exec(s);
  if (tag) errors.push(`có thẻ HTML: "${tag[0].slice(0, 20)}"`);
  const p = /\.\.[\\/]|~[\\/]|\b[A-Za-z]:\\|(?:^|[^\w])\.env\b|\.ssh\b|\/etc\//.exec(s);
  if (p) errors.push(`có đường dẫn: "${p[0].trim().slice(0, 20)}"`);
  return errors;
}
function warningsOf(s) {
  const low = s.toLowerCase();
  const hit = WARN_WORDS.filter((w) => new RegExp(`(^|[^\\p{L}\\p{N}])${w.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|[^\\p{L}\\p{N}])`, 'u').test(low));
  return hit.length ? [`chữ cần đọc kỹ: ${hit.join(', ')}`] : [];
}
function sizeErrors(s, { bytes, lines, lineChars }, what) {
  const errors = [];
  const L = s.split('\n');
  if (Buffer.byteLength(s) > bytes) errors.push(`${what} > ${bytes / 1024} KB`);
  if (L.length > lines) errors.push(`${what} > ${lines} dòng`);
  const long = L.findIndex((l) => l.length > lineChars);
  if (long >= 0) errors.push(`dòng ${long + 1} dài > ${lineChars} ký tự`);
  return errors;
}

// ---------- guidance (mẫu dựng) ----------
/** Frontmatter YAML giản lược của GUIDANCE-SPEC (khoá: giá trị, mảng [a, b]). Bỏ phần chú thích # sau giá trị. */
export function parseFrontmatter(text) {
  const m = /^---\n([\s\S]*?)\n---\n/.exec(text);
  if (!m) return null;
  const fm = {};
  const errors = [];
  for (const raw of m[1].split('\n')) {
    if (!raw.trim()) continue;
    const mm = /^([a-z_]+):\s*(.*)$/.exec(raw);
    if (!mm) { errors.push(`frontmatter: dòng lạ "${raw.slice(0, 40)}"`); continue; }
    let v = mm[2].replace(/\s+#.*$/, '').trim();
    if (Object.prototype.hasOwnProperty.call(fm, mm[1])) errors.push(`frontmatter: khoá ${mm[1]} lặp`);
    if (/^\[.*\]$/.test(v)) v = v.slice(1, -1).split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
    else if (/^".*"$|^'.*'$/.test(v)) v = v.slice(1, -1);
    else if (v === 'true' || v === 'false') v = v === 'true';
    else if (/^-?\d+(\.\d+)?$/.test(v)) v = Number(v);
    fm[mm[1]] = v;
  }
  return { fm, errors, end: m[0].length };
}

export function lintGuidance(md) {
  const n = normalizeText(md);
  const errors = [...n.errors];
  const s = n.text;
  if (errors.length) return { errors, warnings: [], frontmatter: null, text: s };
  errors.push(...sizeErrors(s, LIMITS.template, 'guidance'));
  const p = parseFrontmatter(s);
  let fm = null;
  if (!p) errors.push('thiếu frontmatter --- … --- ở đầu file');
  else {
    fm = p.fm;
    errors.push(...p.errors);
    const keys = Object.keys(fm);
    const extra = keys.filter((k) => !FRONTMATTER_KEYS.includes(k) && !FRONTMATTER_OPTIONAL.includes(k));
    const missing = FRONTMATTER_KEYS.filter((k) => !keys.includes(k));
    if (extra.length) errors.push(`frontmatter có khoá lạ: ${extra.join(', ')}`);
    if (missing.length) errors.push(`frontmatter thiếu khoá: ${missing.join(', ')}`);
    const str = (k, max) => { if (k in fm && (typeof fm[k] !== 'string' || !fm[k].trim() || fm[k].length > max)) errors.push(`frontmatter ${k}: phải là chữ 1–${max} ký tự`); };
    str('id', 40); str('title', 80); str('genre', 100); str('blurb', 200);
    if ('category' in fm && !CATEGORIES.includes(fm.category)) errors.push(`frontmatter category "${fm.category}" không thuộc ${CATEGORIES.join('|')}`);
    if ('technique' in fm && (!Array.isArray(fm.technique) || !fm.technique.length || fm.technique.some((t) => !TECHNIQUES.includes(t)))) errors.push(`frontmatter technique phải là mảng con của ${TECHNIQUES.join('|')}`);
    if ('difficulty' in fm && !(Number.isInteger(fm.difficulty) && fm.difficulty >= 1 && fm.difficulty <= 5)) errors.push('frontmatter difficulty phải là số nguyên 1–5');
    if ('aspect' in fm && fm.aspect !== '9:16') errors.push('frontmatter aspect phải là "9:16"');
    if ('duration_s' in fm && !(typeof fm.duration_s === 'number' && fm.duration_s >= 3 && fm.duration_s <= 60)) errors.push('frontmatter duration_s phải là số 3–60');
    if ('narration' in fm && typeof fm.narration !== 'boolean') errors.push('frontmatter narration phải là true/false');
  }
  const body = p ? s.slice(p.end) : s;
  const heads = body.split('\n').filter((l) => /^##\s/.test(l)).map((l) => l.replace(/^##\s+/, '').trim());
  if (heads.join('|') !== SECTIONS.join('|')) {
    const firstBad = SECTIONS.findIndex((h, i) => heads[i] !== h);
    errors.push(`các mục ## phải đúng 12 mục theo GUIDANCE-SPEC, đúng thứ tự (lệch ở mục ${firstBad >= 0 ? firstBad + 1 : heads.length + 1}: thấy "${heads[firstBad] ?? heads[SECTIONS.length] ?? '(không có)'}")`);
  }
  if (/^#\s/m.test(body)) errors.push('không được có tiêu đề # cấp 1 trong guidance');
  errors.push(...contentErrors(s));
  return { errors, warnings: warningsOf(s), frontmatter: fm, text: s };
}

// ---------- cách dựng Edit ----------
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
function depthOf(v) { return v && typeof v === 'object' ? 1 + Math.max(0, ...Object.values(v).map(depthOf)) : 0; }
function hasForbiddenKey(raw) { return /"(?:__proto__|constructor|prototype)"\s*:/.test(raw); }

const SHADOW_RE = /^(?:-?\d+(?:\.\d+)?(?:px)?\s+){2,3}(?:rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(?:,\s*(?:0|1|0?\.\d+)\s*)?\)|#[0-9A-Fa-f]{6})$/;
const COLOR = { t: 'color' };
const num = (min, max, int = false) => ({ t: 'num', min, max, int });
const bool = { t: 'bool' };
const oneOf = (vals, nullable = false) => ({ t: 'enum', vals, nullable });
// chữ hiển thị (tên, tóm tắt): cấm < > { } ` \ và ký tự điều khiển; UI vẫn phải coi là chữ thường (L9)
// eslint-disable-next-line no-control-regex
const text = (max, re = /^[^<>{}`\\\u0000-\u001f]*$/u) => ({ t: 'str', max, re });
const range = (min, max) => ({ t: 'range', min, max });
const obj = (props) => ({ t: 'obj', props });
const font = { t: 'font' };

/** Schema preset (additionalProperties: false ở mọi tầng). Khoảng số theo applyOverrides (edit/planner.mjs) + THIET-KE L7. */
export function styleSchema() {
  const sfx = oneOf(SFX_NAMES, true);
  return obj({
    id: { t: 'str', max: 32, re: /^[a-z][a-z0-9-]{1,31}$/ },
    name: text(60), nameEn: text(60), summary: text(140), summaryEn: text(140),
    version: num(1, 99, true), order: num(0, 999, true),
    pause: num(0.15, 3), pauseKeep: num(0.15, 3), cutFillers: bool,
    target: num(5, 180), maxSec: num(5, 180),
    captions: obj({ style: oneOf(CAPTION_LOOKS), maxWords: num(1, 8, true), position: oneOf(['lower', 'middle', 'upper']), font, highlightsPerMinute: num(0, 40), numbers: bool }),
    zoom: obj({ kind: oneOf(['punch', 'push']), scale: num(1, 1.6), dur: num(0.2, 8), minGap: num(0.8, 60), perMinute: range(0, 60) }),
    sfx: obj({ onZoom: sfx, max: num(0, 60, true), gainDb: num(-30, 0) }),
    music: obj({ gainDb: num(-40, 0), duckDb: num(0, 24), fadeOut: num(0, 6), default: oneOf(MUSIC_STYLES, true) }),
    graphics: obj({ accent: COLOR, perMinute: range(0, 40), types: { t: 'set', vals: GRAPHIC_TYPES }, zoom: { t: 'num', min: 1, max: 1.3, nullable: true },
      sfxBig: sfx, sfxSmall: sfx, sfxStamp: sfx, sfxTick: sfx, sfxGainDb: num(-30, 0), pinFirst: bool, stepTracker: bool }),
    hook: obj({ pullToFront: bool, maxSec: num(0.5, 6), repeatInPlace: bool, flash: bool, sfx,
      text: obj({ maxChars: num(4, 40, true), until: num(0.5, 6), font, size: num(40, 220), color: COLOR, hi: COLOR, cy: num(0.05, 0.95) }) }),
    look: obj({ font, weight: oneOf([100, 200, 300, 400, 500, 600, 700, 800, 900]), size: num(36, 220), upper: bool, color: COLOR, hi: COLOR,
      karaoke: bool, cy: num(0.05, 0.95), enter: oneOf(LOOK_ENTERS), stroke: num(0, 12), shadow: { t: 'str', max: 60, re: SHADOW_RE },
      box: obj({ bg: COLOR, full: bool, align: oneOf(['left', 'center', 'right']), stroke: num(0, 12), tag: text(16, /^[\p{L}\p{N} !?.,-]*$/u), tagBg: COLOR }),
      quote: obj({ font, weight: oneOf([100, 200, 300, 400, 500, 600, 700, 800, 900]), size: num(36, 220), italic: bool, color: COLOR, marks: COLOR,
        cy: num(0.05, 0.95), blurPx: num(0, 30), dimIn: num(0, 3), dimTo: num(0, 1), wordStagger: num(0, 1) }) }),
  });
}

/** Kiểm + kẹp theo schema. Trả bản đã kẹp; lỗi/cảnh báo đẩy vào mảng. */
function applySchema(v, sc, where, errors, warnings, fonts) {
  const bad = (msg) => { errors.push(`preset ${where}: ${msg}`); return undefined; };
  if (sc.nullable && v === null) return null;
  switch (sc.t) {
    case 'obj': {
      if (!v || typeof v !== 'object' || Array.isArray(v)) return bad('phải là object');
      const out = {};
      for (const [k, x] of Object.entries(v)) {
        if (FORBIDDEN_KEYS.has(k)) { bad(`khoá cấm "${k}"`); continue; }
        if (!Object.prototype.hasOwnProperty.call(sc.props, k)) { bad(`khoá lạ "${k}"`); continue; }
        const r = applySchema(x, sc.props[k], where ? `${where}.${k}` : k, errors, warnings, fonts);
        if (r !== undefined) out[k] = r;
      }
      return out;
    }
    case 'num': {
      if (typeof v !== 'number' || !Number.isFinite(v)) return bad('phải là số');
      let x = sc.int ? Math.round(v) : v;
      if (x < sc.min || x > sc.max) { x = Math.min(sc.max, Math.max(sc.min, x)); warnings.push(`preset ${where}: ${v} ngoài khoảng ${sc.min}–${sc.max}, kẹp thành ${x}`); }
      return x;
    }
    case 'range': {
      if (!Array.isArray(v) || v.length !== 2 || v.some((x) => typeof x !== 'number' || !Number.isFinite(x))) return bad('phải là [min, max]');
      const c = v.map((x) => Math.min(sc.max, Math.max(sc.min, x)));
      if (c[0] > c[1]) c.reverse();
      if (c.some((x, i) => x !== v[i])) warnings.push(`preset ${where}: kẹp thành [${c.join(', ')}]`);
      return c;
    }
    case 'bool': return typeof v === 'boolean' ? v : bad('phải là true/false');
    case 'enum': return sc.vals.includes(v) ? v : bad(`"${String(v).slice(0, 30)}" không thuộc tập cho phép`);
    case 'set': {
      if (!Array.isArray(v) || v.length > sc.vals.length || v.some((x) => !sc.vals.includes(x))) return bad(`phải là mảng con của ${sc.vals.join(', ')}`);
      return [...new Set(v)];
    }
    case 'color': return typeof v === 'string' && /^#[0-9A-Fa-f]{6}$/.test(v) ? v : bad('màu phải dạng #RRGGBB');
    case 'font': {
      const f = typeof v === 'string' ? v.replace(/^'|'$/g, '').replace(/^"|"$/g, '') : '';
      if (!fonts.length) { warnings.push('chưa có engine/fonts/fonts.json: bỏ qua kiểm font'); return v; }
      return fonts.includes(f) ? v : bad(`font "${String(v).slice(0, 30)}" không có trong engine/fonts`);
    }
    case 'str': {
      if (typeof v !== 'string' || v.length > sc.max || !sc.re.test(v)) return bad(`chuỗi không hợp lệ (≤ ${sc.max} ký tự, chỉ chữ/số/dấu thường)`);
      return v;
    }
    default: return bad('schema lạ');
  }
}

/** Tách khối ---json … --- và phần hướng dẫn (đúng như edit/planner.mjs loadStyle). */
export function splitStyle(text) {
  const m = /^---json\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/.exec(text);
  return m ? { json: m[1], guide: m[2] } : null;
}

export function lintEditStyle(md, { slug } = {}) {
  const n = normalizeText(md);
  const errors = [...n.errors];
  const warnings = [];
  const s = n.text;
  if (errors.length) return { errors, warnings, preset: null, guide: '', text: s };
  const parts = splitStyle(s);
  if (!parts) return { errors: ['thiếu khối ---json … --- ở đầu file'], warnings, preset: null, guide: '', text: s };
  if (Buffer.byteLength(parts.json) > LIMITS.style.jsonBytes) errors.push(`khối JSON > ${LIMITS.style.jsonBytes / 1024} KB`);
  if (hasForbiddenKey(parts.json)) errors.push('khối JSON có khoá cấm (__proto__ / constructor / prototype)');
  let raw = null;
  try { raw = JSON.parse(parts.json); } catch (e) { errors.push('khối JSON hỏng: ' + e.message.slice(0, 80)); }
  let preset = null;
  if (raw !== null) {
    if (depthOf(raw) > LIMITS.style.jsonDepth) errors.push(`khối JSON sâu > ${LIMITS.style.jsonDepth} tầng`);
    if (!errors.length) {
      preset = applySchema(raw, styleSchema(), '', errors, warnings, fontFamilies());
      for (const k of ['id', 'name', 'captions']) if (preset && !(k in preset)) errors.push(`preset thiếu "${k}"`);
      if (slug && preset?.id !== slug) errors.push(`preset id "${preset?.id}" phải trùng slug "${slug}"`);
    }
  }
  const guide = parts.guide;
  errors.push(...sizeErrors(guide, { bytes: LIMITS.style.guideBytes, lines: LIMITS.style.guideLines, lineChars: LIMITS.style.lineChars }, 'phần hướng dẫn'));
  const heads = guide.split('\n').filter((l) => /^##\s/.test(l)).map((l) => l.replace(/^##\s+/, '').trim());
  const badHeads = heads.filter((h) => !STYLE_SECTIONS.includes(h));
  if (badHeads.length) errors.push(`mục lạ trong cách dựng: ${badHeads.join(', ')} (chỉ: ${STYLE_SECTIONS.join(', ')})`);
  if (new Set(heads).size !== heads.length) errors.push('mục ## bị lặp');
  if (/^#{3,}\s/m.test(guide)) errors.push('không dùng tiêu đề ### trong cách dựng');
  errors.push(...contentErrors(guide));
  // chuỗi trong preset cũng không được mang URL / thẻ / đường dẫn
  if (raw) errors.push(...contentErrors(JSON.stringify(raw)).map((e) => 'preset: ' + e));
  warnings.push(...warningsOf(guide));
  return { errors, warnings, preset: errors.length ? null : preset, guide: guide.trim(), text: s };
}

// ---------- ảnh ----------
/** Chỉ nhận webp thật (RIFF….WEBP), ≤ 200 KB, ≤ 1080×1920 (đọc từ header VP8 / VP8L / VP8X). */
export function lintWebp(buf) {
  const errors = [];
  if (!Buffer.isBuffer(buf)) return { errors: ['ảnh không phải dữ liệu nhị phân'] };
  if (buf.length > LIMITS.thumb.bytes) errors.push(`ảnh > ${LIMITS.thumb.bytes / 1024} KB`);
  if (buf.length < 30 || buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WEBP') return { errors: [...errors, 'ảnh không phải WebP'] };
  const kind = buf.toString('latin1', 12, 16);
  let w = 0; let h = 0;
  if (kind === 'VP8 ') { w = buf.readUInt16LE(26) & 0x3fff; h = buf.readUInt16LE(28) & 0x3fff; }
  else if (kind === 'VP8L') { const b = buf.readUInt32LE(21); w = (b & 0x3fff) + 1; h = ((b >> 14) & 0x3fff) + 1; }
  else if (kind === 'VP8X') { w = buf.readUIntLE(24, 3) + 1; h = buf.readUIntLE(27, 3) + 1; }
  else errors.push('ảnh WebP lạ');
  if (w > LIMITS.thumb.maxW || h > LIMITS.thumb.maxH || !w || !h) errors.push(`kích thước ảnh ${w}×${h} vượt ${LIMITS.thumb.maxW}×${LIMITS.thumb.maxH}`);
  return { errors, width: w, height: h };
}

// ---------- chạy trên mẫu gốc ----------
if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
  let bad = 0; let warn = 0;
  const gdir = path.join(ROOT, 'templates', 'guidance');
  const gs = fs.readdirSync(gdir).filter((f) => f.endsWith('.md'));
  for (const f of gs) {
    const r = lintGuidance(fs.readFileSync(path.join(gdir, f)));
    if (r.errors.length) { bad++; console.log(`LỖI ${f}: ${r.errors.join(' | ')}`); }
    if (r.warnings.length) warn++;
  }
  const sdir = path.join(ROOT, 'edit-styles');
  const ss = fs.readdirSync(sdir).filter((f) => f.endsWith('.md'));
  for (const f of ss) {
    const r = lintEditStyle(fs.readFileSync(path.join(sdir, f)), { slug: f.slice(0, -3) });
    if (r.errors.length) { bad++; console.log(`LỖI ${f}: ${r.errors.join(' | ')}`); }
    for (const w of r.warnings.filter((x) => x.startsWith('preset'))) console.log(`kẹp ${f}: ${w}`);
    if (r.warnings.length) warn++;
  }
  for (const d of [path.join(ROOT, 'templates', 'thumbs'), path.join(sdir, 'thumbs')]) {
    for (const f of fs.readdirSync(d).filter((x) => x.endsWith('.webp'))) {
      const r = lintWebp(fs.readFileSync(path.join(d, f)));
      if (r.errors.length) { bad++; console.log(`LỖI ảnh ${f}: ${r.errors.join(' | ')}`); }
    }
  }
  console.log(`${gs.length} guidance + ${ss.length} cách dựng + ảnh: ${bad} file lỗi, ${warn} file có chữ cần đọc kỹ`);
  process.exit(bad ? 1 : 0);
}