Skip to content

Rules for an AI coding agent to filter out generic AI-generated UI designs, text, and code.

14.1 KB
Raw Blame
#!/usr/bin/env node
/**
 * The rules antislop applies to other people's repos, applied to this one.
 * Run it before opening a PR:
 *
 *   node scripts/check-repo.mjs
 */
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { buildIndex, START, END } from './skill-index.mjs'

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
const read = (p) => fs.readFileSync(path.join(root, p), 'utf8')
// Split on /\r?\n/, not '\n': on a Windows checkout a trailing \r survives and
// every ^...$ regex below silently stops matching.
const lines = (p) => read(p).split(/\r?\n/)

const SKILLS = fs
  .readdirSync(path.join(root, 'skills'), { withFileTypes: true })
  .filter((e) => e.isDirectory())
  .map((e) => `skills/${e.name}/SKILL.md`)

const MANIFESTS = [
  'package.json',
  '.claude-plugin/plugin.json',
  '.claude-plugin/marketplace.json',
  '.codex-plugin/plugin.json',
  '.cursor-plugin/plugin.json',
  '.cursor-plugin/marketplace.json',
  '.kimi-plugin/plugin.json',
  '.agents/plugins/marketplace.json',
  '.omp-plugin/marketplace.json',
  'plugin.json',
  'cli/package.json',
]

/** The community files GitHub reads. Held to the rules the documents above already follow. */
const COMMUNITY = [
  'CONTRIBUTING.md',
  'CODE_OF_CONDUCT.md',
  '.github/PULL_REQUEST_TEMPLATE.md',
  '.github/ISSUE_TEMPLATE/bug_report.yml',
  '.github/ISSUE_TEMPLATE/rule_gap.yml',
  '.github/ISSUE_TEMPLATE/config.yml',
]

/** R-02's carve-out, encoded so a new em dash in ordinary prose still fails. */
function emDashes() {
  const bad = []
  // The rules/ pointers ship to plugin users, so the ban covers them like any other doc.
  const files = [
    'antislop.md',
    'README.md',
    'GUIDE.md',
    'ROADMAP.md',
    'SECURITY.md',
    'rules/antislop.md',
    'rules/antislop.mdc',
    ...COMMUNITY,
    ...SKILLS,
  ]

  for (const file of files) {
    let section = ''
    lines(file).forEach((line, i) => {
      const heading = line.match(/^#{2,4}\s+(.*)$/)
      if (heading) section = heading[1]
      if (!/[—–]/.test(line)) return

      const exempt =
        // "#### R-02 — Copywriting" and "### C-1 — Intentionality"
        /^#{2,4}\s+(R-\d{2}|C-\d)\s+—\s/.test(line) ||
        // The rule that defines the ban, and the skill section that teaches it.
        /^(R-02|Em Dashes)\b/.test(section) ||
        // The Part 1 table row that shows the pattern.
        /^\|\s*\*\*Em Dash/.test(line) ||
        // The Delivery Gate item that quotes the character it checks for.
        (/^\s*- \[ \]/.test(line) && /\*\(R-02\)\*/.test(line))

      if (!exempt) bad.push(`${file}:${i + 1}: ${line.trim().slice(0, 90)}`)
    })
  }
  return bad
}

/** Every rule the core defines must have a Delivery Gate item citing it, and vice versa. */
function gateCoverage() {
  const core = read('antislop.md')
  const defined = new Set([...core.matchAll(/^#### (R-\d{2}) —/gm)].map((m) => m[1]))
  const gate = core.split('## Delivery Gate (Mandatory)')[1] ?? ''
  const cited = new Set([...gate.matchAll(/\((R-\d{2})\)/g)].map((m) => m[1]))

  const bad = []
  for (const r of [...defined].sort()) {
    if (!cited.has(r)) bad.push(`${r} is defined in Part 2 but no Delivery Gate item cites it`)
  }
  for (const r of [...cited].sort()) {
    if (!defined.has(r)) bad.push(`${r} is cited in the Delivery Gate but Part 2 does not define it`)
  }
  return bad
}

/** A skill may reference core rules by number. It may not invent one. */
function skillReferences() {
  const defined = new Set([...read('antislop.md').matchAll(/^#### (R-\d{2}) —/gm)].map((m) => m[1]))
  const bad = []
  for (const file of SKILLS) {
    for (const r of new Set([...read(file).matchAll(/\bR-\d{2}\b/g)].map((m) => m[0]))) {
      if (!defined.has(r)) bad.push(`${file} cites ${r}, which antislop.md does not define`)
    }
  }
  return bad
}

/** The version is hand-written in every manifest and stamp. They have to agree. */
function versions() {
  // A malformed file is already reported by the manifest check; do not crash here.
  const json = (p) => {
    try {
      return JSON.parse(read(p))
    } catch {
      return null
    }
  }
  const want = json('cli/package.json')?.version
  if (!want) return ['cli/package.json has no readable version']

  const found = [
    // The lock file carries the version twice, and npm ci will not correct a stale one.
    ['cli/package-lock.json', json('cli/package-lock.json')?.version],
    ['cli/package-lock.json (packages "")', json('cli/package-lock.json')?.packages?.['']?.version],
    // The Cline plugin manifest and, from v3.2.17, the Pi package. Same release.
    ['package.json', json('package.json')?.version],
    ['.claude-plugin/plugin.json', json('.claude-plugin/plugin.json')?.version],
    ['.claude-plugin/marketplace.json', json('.claude-plugin/marketplace.json')?.plugins?.[0]?.version],
    ['.codex-plugin/plugin.json', json('.codex-plugin/plugin.json')?.version],
    ['.cursor-plugin/plugin.json', json('.cursor-plugin/plugin.json')?.version],
    ['.omp-plugin/marketplace.json', json('.omp-plugin/marketplace.json')?.plugins?.[0]?.version],
    ['.kimi-plugin/plugin.json', json('.kimi-plugin/plugin.json')?.version],
    // Stamped into every install, so a stale one makes the installer misreport what is on disk.
    ['skills/antislop/VERSION', read('skills/antislop/VERSION').trim()],
    ['cli/lib/banner.mjs', read('cli/lib/banner.mjs').match(/installer v(\d+\.\d+\.\d+)/)?.[1]],
    ['skills/antislop-human/contrast-mcp.py', read('skills/antislop-human/contrast-mcp.py').match(/SERVER_VERSION = "(\d+\.\d+\.\d+)"/)?.[1]],
    // The contributors image is cached per URL, so a changed version is what makes it redraw.
    ['README.md (contributors image)', read('README.md').match(/contrib\.rocks\/image\?repo=[^"'&\s]+&v=(\d+\.\d+\.\d+)/)?.[1]],
  ]

  return found
    .filter(([, got]) => got !== want)
    .map(([file, got]) => `${file} says ${got ?? 'nothing'}, cli/package.json says ${want}`)
}

/** A manifest that does not parse takes its whole install path down. */
function manifests() {
  const bad = []
  for (const file of MANIFESTS) {
    try {
      JSON.parse(read(file))
    } catch (err) {
      bad.push(`${file} is not valid JSON: ${err.message}`)
    }
  }
  return bad
}

/** An agent finds a skill by its frontmatter. Without it the folder is inert. */
function frontmatter() {
  const bad = []
  for (const file of SKILLS) {
    const head = read(file).split('---')[1] ?? ''
    // [ \t] not \s: \s spans newlines, so an empty value would match the next key.
    if (!/^name:[ \t]*\S/m.test(head)) bad.push(`${file} has no name in its frontmatter`)
    if (!/^description:[ \t]*\S/m.test(head)) bad.push(`${file} has no description in its frontmatter`)
  }
  return bad
}

/** A new skill has to be registered in all four places below or it cannot install. */
function registration() {
  const names = SKILLS.map((f) => f.split('/')[1])
  const core = 'antislop'
  const places = [
    ['rules/antislop.md', read('rules/antislop.md')],
    ['rules/antislop.mdc', read('rules/antislop.mdc')],
    ["cli/index.mjs (EXTRA_SKILLS)", read('cli/index.mjs')],
    ['cli/lib/install.mjs (SKILL_LINES)', read('cli/lib/install.mjs')],
  ]

  const bad = []
  for (const name of names) {
    for (const [label, text] of places) {
      // The core is always on, so the picker's optional-extras menu never lists it.
      if (name === core && label.startsWith('cli/index.mjs')) continue
      if (!text.includes(name)) bad.push(`${name} is not registered in ${label}`)
    }
  }
  return bad
}

/** A rule's tier decides its gate block: Hard Gate 1, Purpose-Gate 2, Quality Locks 4. */
function tiers() {
  const core = read('antislop.md')
  const part2 = core.split('## Part 2:')[1]?.split('## Part 3:')[0] ?? ''

  const group = {}
  let current = null
  for (const line of part2.split('\n')) {
    const g = line.match(/^### Group \d: ([^(]+)/)
    if (g) current = g[1].trim()
    const r = line.match(/^#### (R-\d{2}) —/)
    if (r && current) group[r[1]] = current
  }

  const block = {}
  let currentBlock = null
  for (const line of (core.split('## Delivery Gate (Mandatory)')[1] ?? '').split('\n')) {
    const b = line.match(/^### (Block \d):/)
    if (b) currentBlock = b[1]
    for (const m of line.matchAll(/\((R-\d{2})\)/g)) {
      if (!block[m[1]]) block[m[1]] = currentBlock
    }
  }

  const wants = { 'Hard Gate': 'Block 1', 'Purpose-Gate': 'Block 2', 'Quality Locks': 'Block 4' }
  const bad = []
  for (const [rule, grp] of Object.entries(group).sort()) {
    const want = wants[grp]
    const got = block[rule]
    if (want && got && want !== got) bad.push(`${rule} is a ${grp} rule but the gate cites it from ${got}`)
  }
  return bad
}

/** A manifest that points at a file that is gone breaks its install path quietly. */
function manifestPaths() {
  const bad = []
  for (const file of MANIFESTS) {
    let text
    try {
      text = read(file)
    } catch {
      continue
    }
    for (const m of text.matchAll(/"(\.\/[^"]+)"/g)) {
      const target = m[1].replace(/^\.\//, '')
      if (!existsExactly(target)) bad.push(`${file} points at ${m[1]}, which does not exist`)
    }
    // A plugin-root path is absolute only once the agent expands it, so check the tail.
    for (const m of text.matchAll(/"\$\{CLAUDE_PLUGIN_ROOT\}\/([^"]+)"/g)) {
      if (!existsExactly(m[1])) bad.push(`${file} points at \${CLAUDE_PLUGIN_ROOT}/${m[1]}, which does not exist`)
    }
  }
  return bad
}

/** existsSync misses a case-only rename on macOS; compare the real dir entry. */
const existsExactly = (target) => {
  const full = path.join(root, target)
  const dir = path.dirname(full)
  if (!fs.existsSync(dir)) return false
  return fs.readdirSync(dir).includes(path.basename(full))
}

/** GitHub's anchor rule: lowercase, drop punctuation, spaces to hyphens, duplicates numbered. */
function anchorsIn(text) {
  const taken = new Map()
  const out = new Set()
  for (const line of text.split(/\r?\n/)) {
    const m = line.match(/^#{1,6}\s+(.+?)\s*#*\s*$/)
    if (!m) continue
    const base = m[1].toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, '').trim().replace(/\s+/g, '-')
    const seen = taken.get(base) ?? 0
    taken.set(base, seen + 1)
    out.add(seen === 0 ? base : `${base}-${seen}`)
  }
  return out
}

function docLinks() {
  const bad = []
  for (const file of ['README.md', 'GUIDE.md', 'ROADMAP.md', 'SECURITY.md', ...COMMUNITY]) {
    // Markdown links, plus the raw HTML images and badges the README is built from.
    for (const m of read(file).matchAll(/\]\(([^)\s]+)\)|(?:src|href)="([^"]+)"/g)) {
      const [target, anchor] = (m[1] ?? m[2]).split('#')
      if (/^(https?:|mailto:)/.test(target)) continue
      // Every table of contents is a list of these, and a renamed heading breaks one silently.
      if (!target) {
        if (anchor && !anchorsIn(read(file)).has(anchor)) {
          bad.push(`${file} links to #${anchor}, which is not a heading in it`)
        }
        continue
      }
      if (!existsExactly(target)) {
        bad.push(`${file} links to ${target}, which does not exist`)
        continue
      }
      if (anchor && target.endsWith('.md') && !anchorsIn(read(target)).has(anchor)) {
        bad.push(`${file} links to ${target}#${anchor}, which is not a heading in it`)
      }
    }
  }
  return bad
}

/** A YAML file that routes people by URL rots the same way a markdown link does. */
function repoUrls() {
  const bad = []
  const prefix = 'https://github.com/miqdadbadjuber/anti-slop/blob/main/'
  for (const file of COMMUNITY) {
    for (const m of read(file).matchAll(/url:\s*(\S+)/g)) {
      // A URL that leaves this repository is not this check's to resolve.
      if (!m[1].startsWith(prefix)) continue
      const target = m[1].slice(prefix.length)
      if (!existsExactly(target)) bad.push(`${file} points at ${target}, which does not exist`)
    }
  }
  return bad
}

/** The WCAG formula is duplicated, and only contrast-check.py has a selftest. */
function contrastTwins() {
  const check = read('skills/antislop-human/contrast-check.py')
  const mcp = read('skills/antislop-human/contrast-mcp.py')
  const constants = ['0.03928', '12.92', '1.055', '0.2126', '0.7152', '0.0722', '0.05']

  const bad = []
  for (const c of constants) {
    if (check.includes(c) !== mcp.includes(c)) {
      bad.push(`the WCAG constant ${c} appears in only one of contrast-check.py and contrast-mcp.py`)
    }
  }
  return bad
}

/** The guide carries a generated catalogue, so a skill that adds a pattern cannot leave it behind. */
function skillIndex() {
  const guide = read('GUIDE.md').replace(/\r\n/g, '\n')
  const from = guide.indexOf(START)
  const to = guide.indexOf(END)
  if (from === -1 || to === -1) return [`GUIDE.md has no ${START} ... ${END} pair`]

  let generated
  try {
    generated = buildIndex()
  } catch (e) {
    return [e.message]
  }
  const shipped = guide.slice(from + START.length, to).replace(/^\n+|\n+$/g, '')
  if (shipped !== generated.replace(/\n+$/, '')) {
    return ['the skill catalogue in GUIDE.md is stale: run node scripts/skill-index.mjs']
  }
  return []
}

const CHECKS = [
  // Manifests first: the later checks read them as data.
  ['every manifest is valid JSON', manifests],
  ['no em dash outside the R-02 carve-out', emDashes],
  ['every rule has a Delivery Gate item', gateCoverage],
  ['skills cite only rules that exist', skillReferences],
  ['the version agrees everywhere', versions],
  ['every skill has usable frontmatter', frontmatter],
  ['every skill is registered everywhere', registration],
  ['each rule sits in the gate block its tier implies', tiers],
  ['every manifest path resolves', manifestPaths],
  ['every doc link resolves', docLinks],
  ['every URL in a community file resolves', repoUrls],
  ['both contrast implementations use the same formula', contrastTwins],
  ['the skill index in the guide is current', skillIndex],
]

let failed = 0
for (const [label, run] of CHECKS) {
  const problems = run()
  if (problems.length === 0) {
    console.log(`ok   ${label}`)
    continue
  }
  failed += 1
  console.log(`FAIL ${label}`)
  for (const p of problems) console.log(`       ${p}`)
}

if (failed > 0) {
  console.error(`\n${failed} of ${CHECKS.length} checks failed`)
  process.exit(1)
}
console.log(`\nall ${CHECKS.length} checks passed`)