// --- Types --- export interface Alert { check: string; severity: "error" | "warning" | "suggestion"; message: string; line: number; span: [number, number]; // character offset within the line match: string; action: { name: string; params: string[] } | null; } export interface LintResult { alerts: Alert[]; summary: { total: number; errors: number; warnings: number; suggestions: number; }; } // --- Rule types (mirrors Vale's YAML rule format) --- interface ExistenceRule { type: "existence"; check: string; message: string; level: "error" | "warning" | "suggestion"; ignorecase?: boolean; // Vale wraps tokens in \b word boundaries unless nonword: true nonword?: boolean; scope?: "heading" | "sentence" | "text"; tokens: string[]; action?: { name: string; params: string[] }; } interface SubstitutionRule { type: "substitution"; check: string; message: string; level: "error" | "warning" | "suggestion"; ignorecase?: boolean; nonword?: boolean; // empty value means "cut the word entirely" swap: Record; action?: { name: string; params: string[] }; } interface OccurrenceRule { type: "occurrence"; check: string; message: string; level: "error" | "warning" | "suggestion"; // whole-document count (Vale's scope: text); alert fires once, // anchored at the first occurrence past max max: number; token: string; } type Rule = ExistenceRule | SubstitutionRule | OccurrenceRule; // --- The Unslop style --- // Ported from a local Vale style targeting AI-slop writing patterns. const rules: Rule[] = [ { type: "existence", check: "Unslop.AISignatures", message: "Possible AI slop pattern: '%s' — review whether this rhetorical move is doing real work or is just a tic.", level: "warning", ignorecase: true, tokens: [ // Negation-then-correction: "X isn't/wasn't/don't Y. It's/They Z." "wasn't [^.]+\\. It was", "wasn't [^.]+\\. It's", "wasn't [^.]+\\. It ", "isn't [^.]+\\. It's", "isn't [^.]+\\. It ", "isn't [^.]+\\. That's", "isn't [^.]+\\. That ", "don't [^.]+\\. They ", "don't [^.]+\\. It ", "doesn't [^.]+\\. It ", "doesn't [^.]+\\. They ", "aren't [^.]+\\. They", "weren't [^.]+\\. They", "can't [^.]+\\. You ", "can't [^.]+\\. It ", "couldn't [^.]+\\. It ", "wouldn't [^.]+\\. It ", // "not just X" inversions "not just [^.]+\\. That's", "not just [^.]+\\. It's", "not just [^.]+\\. It ", "That's not just", "That's not [^.]+\\. That's", "That's not [^.]+\\. It's", "It's not [^.]+\\. It's", "It's not [^.]+\\. That's", "It's not [^.]+\\. That ", // "not about X, it's about Y" "It's not about [^.]+, it's about", "It's not about [^.]+\\. It's about", // comma variants of the negation-correction family "It's not [^.]+, it's", "That's not [^.]+, that's", // "Not because X. But because Y." "Not because [^.]+\\. But because", "Not because [^.]+, but because", // "Not by doing X, but by doing Y." "Not by [^.]+, but by", "Not by [^.]+\\. But by", // "No X. No Y. Just Z." "No [^.]+\\. No [^.]+\\. Just", // Rhetorical question setup: "And the X? Y." / "The result? Y." "And the [^.?]+\\?", "The (result|takeaway|catch|kicker|upshot|outcome|point|bottom line)\\?", // Always-bad filler openers "In an era of", "In today's", "Whether you're a", "Think of [^.]+ as", // HIGH false-positive risk: fragment/staccato cadence. Matches structure // only; ignorecase defeats the "capital = sentence start" heuristic, so // these also fire on normal short clauses and fiction. Remove if noisy. // "Focused. Aligned. Measurable." (one-word triad) "\\b\\w+\\. \\w+\\. \\w+[.!]", // "Fewer questions. Less confusion. Better engagement." (two-word triad) "\\b\\w+ \\w+\\. \\w+ \\w+\\. \\w+ \\w+[.!]", ], }, { type: "existence", check: "Unslop.BannedPhrases", message: "Banned phrase: '%s' — rewrite without this pattern.", level: "error", ignorecase: true, tokens: [ "Here's the thing", "Here's why that matters", "Here's where this gets", "here's the kicker", "Let that sink in", "Read that again", "Full stop", "And that changes everything", "In today's fast-paced world", "In today's digital age", "in today's modern age", "in today's rapidly evolving market", "In the ever-evolving landscape", "In the realm of", "in the era of", "Imagine a world where", "picture this", "It's important to note that", "it is important to note", "it is worth noting", "It's worth mentioning that", "important to consider", "Let's delve into", "let's dive in", "In conclusion", "In the final analysis", "All things considered", "At the end of the day", "This begs the question", "game-changer", "paradigm shift", "perfect storm", "seamless integration", "effortless setup", "best-in-class", "world-class", "next-generation", "cutting edge", "state-of-the-art", "unleash", "full potential", "There are two versions", "chaos into clarity", "comes to the rescue", "saves the day", "moves the needle", "nailing down", "scroll stopper", "secret sauce", "secret weapon", "scream into the void", "stay tuned", "welcome to the world", "strategic alignment", "solution development", "operational excellence", "organizational efficiency", "collaborative environment", "cost optimization", "customer loyalty", "customer satisfaction", "customer-centric", "data-driven", "demonstrates significant", "digital transformation", "disruptive innovation", "domain expertise", "driving innovation", "emerging technologies", "encountered hurdles", "ethical considerations", "ever-evolving", "foster innovation", "fresh perspectives", "from inception to execution", "generally speaking", "governance framework", "granular detail", "granular level", "growing recognition", "implementation strategy", "in other words", "insights into", "key takeaways", "knowledge transfer", "market penetration", "mission-critical", "nevertheless", "on the contrary", "on the other hand", "pain point", "particularly in areas", "problem solving", "quality assurance", "reaching new heights", "rapidly evolving", "regulatory compliance", "revenue growth", "risk mitigation", "root cause analysis", "shedding light on", "subject matter experts", "the linchpin of", "the road ahead", "the power of", "thought-provoking", "treasure trove", "transforming the way", "to thrive", "to summarize", "to shed light on", "to showcase", "to underscore", "value proposition", "value-added", "widely recognized", "with regards to", ], }, { type: "occurrence", check: "Unslop.EmDash", message: "Too many em dashes. Use commas, colons, parentheses, or periods instead.", level: "warning", max: 3, token: "—", }, { type: "substitution", check: "Unslop.BuzzKill", message: "Use '%s' instead of '%s'.", level: "error", ignorecase: true, action: { name: "replace", params: [] }, swap: { accelerate: "speed up", accentuate: "stress", adaptive: "flexible", agile: "quick", "AI-powered": "AI", align: "match", "always-on": "24/7", automate: "do automatically", boast: "has", breakthrough: "advance", "cloud-native": "cloud-based", commendable: "good", crucial: "key", customizable: "adjustable", "data-driven": "based on data", democratize: "open up", disruptive: "new", dynamic: "active", effortless: "easy", efficient: "lean", elevate: "lift", emphasize: "stress", empower: "help", enhance: "improve", findings: "results", frictionless: "smooth", "future-proof": "lasting", garner: "get", harness: "use", highlight: "show", "hyper-personalized": "tailored", immersive: "rich", insightful: "useful", integrated: "built-in", intelligent: "clever", intricate: "complex", intuitive: "easy", landscape: "field", "leading-edge": "modern", "machine-first": "", meticulous: "careful", meticulously: "carefully", "mission-critical": "essential", "next-gen": "new", "next-generation": "new", optimize: "improve", paradigm: "model", "paradigm-shifting": "", personalized: "custom", pioneering: "new", "plug-and-play": "ready to use", potential: "promise", proactive: "ahead", predictive: "forecasting", proprietary: "our own", realm: "area", redefine: "change", reimagine: "rethink", reliable: "steady", "results-driven": "", revolutionize: "change", scalable: "able to grow", showcase: "show", showcasing: "showing", smart: "", "state-of-the-art": "modern", surpass: "beat", synergize: "combine", tapestry: "mix", testament: "proof", trailblazing: "new", transparent: "open", turnkey: "ready", unleash: "release", unlock: "open", unparalleled: "unmatched", unprecedented: "new", versatile: "flexible", vibrant: "lively", visionary: "bold", }, }, { type: "existence", check: "Unslop.WeakWords", message: "Weak/filler word '%s' — cut it or replace with something specific.", level: "warning", ignorecase: true, tokens: [ "very", "really", "extremely", "incredibly", "absolutely", "basically", "certainly", "clearly", "definitely", "essentially", "fundamentally", "interestingly", "naturally", "obviously", "significantly", "surely", "truly", "undoubtedly", "furthermore", "moreover", "notwithstanding", "that being said", "at its core", "to put it simply", "in order to", "drift", "shift", "signal", "lands", "landed", ], }, ]; // --- Pattern compilation --- // Vale wraps tokens/swap keys in \b unless nonword: true. \b only works next // to a word character, so only add it on ends that are word characters // (a trailing \b after "?" would silently kill the pattern). function withWordBoundaries(pattern: string): string { const start = /^[A-Za-z0-9]/.test(pattern) ? "\\b" : ""; const end = /[A-Za-z0-9]$/.test(pattern) ? "\\b" : ""; return start + pattern + end; } // Match straight and curly apostrophes interchangeably. function normalizeApostrophes(pattern: string): string { return pattern.replace(/['’]/g, "['’]"); } const regexCache = new Map(); function getRegex( pattern: string, ignorecase: boolean | undefined, nonword: boolean | undefined, ): RegExp { const source = normalizeApostrophes( nonword ? pattern : withWordBoundaries(pattern), ); const flags = ignorecase ? "gi" : "g"; const key = flags + ":" + source; let regex = regexCache.get(key); if (!regex) { regex = new RegExp(source, flags); regexCache.set(key, regex); } regex.lastIndex = 0; return regex; } // --- Markdown scope detection --- interface LineScope { text: string; lineNo: number; scope: "heading" | "text" | "code"; isCodeBlock: boolean; } function parseMarkdown(text: string): LineScope[] { const lines = text.split("\n"); const scopes: LineScope[] = []; let inCodeBlock = false; let codeFence = ""; for (let i = 0; i < lines.length; i++) { const line = lines[i]; // Track fenced code blocks (``` or ~~~) const fenceMatch = line.match(/^(\s*)(```+|~~~+)/); if (fenceMatch) { const fence = fenceMatch[2]; if (!inCodeBlock) { inCodeBlock = true; codeFence = fence; } else if (fence[0] === codeFence[0]) { inCodeBlock = false; codeFence = ""; } scopes.push({ text: line, lineNo: i + 1, scope: "code", isCodeBlock: true, }); continue; } if (inCodeBlock) { scopes.push({ text: line, lineNo: i + 1, scope: "code", isCodeBlock: true, }); continue; } // Detect headings (# or underlined) const headingMatch = line.match(/^(#{1,6})\s+(.*)/); if (headingMatch) { scopes.push({ text: headingMatch[2], lineNo: i + 1, scope: "heading", isCodeBlock: false, }); continue; } // Check for underlined heading (=== or ---) if (i + 1 < lines.length && lines[i].trim() !== "") { const next = lines[i + 1]; if (/^(=+)\s*$/.test(next) || /^(-+)\s*$/.test(next)) { scopes.push({ text: line, lineNo: i + 1, scope: "heading", isCodeBlock: false, }); continue; } } scopes.push({ text: line, lineNo: i + 1, scope: "text", isCodeBlock: false, }); } return scopes; } // Strip inline code from a line so we don't lint `code` // (replaced with spaces of the same length to preserve offsets) function stripInlineCode(text: string): string { return text.replace(/`[^`]+`/g, (match) => " ".repeat(match.length)); } // --- Linter engine --- export function lint(text: string): LintResult { const scopes = parseMarkdown(text); const alerts: Alert[] = []; // whole-document counters for occurrence rules const occurrenceCounts = new Map(); for (const lineScope of scopes) { if (lineScope.scope === "code") continue; const lineText = stripInlineCode(lineScope.text); for (const rule of rules) { if (rule.type === "occurrence") { applyOccurrence( rule, lineText, lineScope.lineNo, occurrenceCounts, alerts, ); } else { alerts.push( ...applyRule(rule, lineText, lineScope.lineNo, lineScope.scope), ); } } } const deduped = dropContainedDuplicates(alerts); // Sort by line, then by position deduped.sort((a, b) => a.line - b.line || a.span[0] - b.span[0]); const summary = { total: deduped.length, errors: deduped.filter((a) => a.severity === "error").length, warnings: deduped.filter((a) => a.severity === "warning").length, suggestions: deduped.filter((a) => a.severity === "suggestion").length, }; return { alerts: deduped, summary }; } // Multiple tokens of one rule can match overlapping text (e.g. "It's not // [^.]+. It's" and "not just [^.]+. It's" on the same sentence). Drop an // alert when another alert from the same check on the same line spans a // superset of it; on identical spans keep the first. function dropContainedDuplicates(alerts: Alert[]): Alert[] { return alerts.filter((a, i) => !alerts.some((b, j) => { if (j === i || b.check !== a.check || b.line !== a.line) return false; if (b.span[0] > a.span[0] || b.span[1] < a.span[1]) return false; const bLen = b.span[1] - b.span[0]; const aLen = a.span[1] - a.span[0]; return bLen > aLen || (bLen === aLen && j < i); }) ); } function applyRule( rule: ExistenceRule | SubstitutionRule, lineText: string, lineNo: number, scope: string, ): Alert[] { if ("scope" in rule && rule.scope && scope !== rule.scope) return []; if (rule.type === "existence") { return applyExistence(rule, lineText, lineNo); } return applySubstitution(rule, lineText, lineNo); } function applyExistence( rule: ExistenceRule, lineText: string, lineNo: number, ): Alert[] { const alerts: Alert[] = []; for (const token of rule.tokens) { const regex = getRegex(token, rule.ignorecase, rule.nonword); let match: RegExpExecArray | null; while ((match = regex.exec(lineText)) !== null) { if (match.index === regex.lastIndex) { regex.lastIndex++; continue; } const matched = match[0]; alerts.push({ check: rule.check, severity: rule.level, message: rule.message.replace("%s", matched.trim()), line: lineNo, span: [match.index, match.index + matched.length], match: matched, action: rule.action ?? null, }); } } return alerts; } function applySubstitution( rule: SubstitutionRule, lineText: string, lineNo: number, ): Alert[] { const alerts: Alert[] = []; for (const [pattern, replacement] of Object.entries(rule.swap)) { const regex = getRegex(pattern, rule.ignorecase, rule.nonword); let match: RegExpExecArray | null; while ((match = regex.exec(lineText)) !== null) { if (match.index === regex.lastIndex) { regex.lastIndex++; continue; } const matched = match[0]; const message = replacement === "" ? `Cut '${matched.trim()}' — it adds nothing.` : rule.message.replace("%s", replacement).replace("%s", matched.trim()); alerts.push({ check: rule.check, severity: rule.level, message, line: lineNo, span: [match.index, match.index + matched.length], match: matched, action: rule.action ?? null, }); } } return alerts; } // Counts token occurrences across the whole document (Vale's scope: text). // Emits a single alert, anchored at the first occurrence past rule.max. function applyOccurrence( rule: OccurrenceRule, lineText: string, lineNo: number, counts: Map, alerts: Alert[], ): void { const regex = getRegex(rule.token, false, true); let count = counts.get(rule) ?? 0; let match: RegExpExecArray | null; while ((match = regex.exec(lineText)) !== null) { if (match.index === regex.lastIndex) { regex.lastIndex++; continue; } count++; if (count === rule.max + 1) { alerts.push({ check: rule.check, severity: rule.level, message: rule.message, line: lineNo, span: [match.index, match.index + match[0].length], match: match[0], action: null, }); } } counts.set(rule, count); }