/** * Avoid AI Writing — detection engine (canonical source of truth) * Implements regex, structural, and stylometric pattern detection. This repo's SKILL.md * catalogs the human-editable pattern rules; this engine is the executable * expression of the regex-detectable subset and extends it with stylometric and * AI-tool-fingerprint detectors that don't make sense as skill prose * (cross-paragraph burstiness, smart-punct signatures, function-word * trigram entropy, low type-token ratio, AI-tool URL parameters, * chatbot citation markup leaks, unfilled placeholders). * * Scoring model: * Each category has a weight in the ISSUE_WEIGHTS table. Detection runs * produce raw (possibly duplicate) issues which are then deduplicated by * (type, text) pair. rawScore is the sum of category weights across the * deduped list — so the number reflects the same distinct signals the * user sees in the issue list. * * Weights are deliberately non-flat across severity tags. Cutoff * disclaimers (10) and chatbot artifacts (8) weigh more than vague * attributions (5), even though all three are tagged `critical`, because * the skill treats them as stronger or weaker AI-origin signals. * * rawScore is then normalized to 0-100 via `log2(wordCount/50)` so longer * texts don't accumulate unboundedly on the same density of patterns. */ const AIDetector = (() => { // ═══ Tier 1 pre-pass: normalize bypass tricks ══════════════════════ // // Humanizer tools and prompt-injection bypass techniques insert // invisible / lookalike chars to defeat exact-string detectors. Strip // them BEFORE pattern matching so "delve" with a Cyrillic 'е' still // hits the Tier 1 list. Unicode ranges sourced from // It-s-AI/llm-detection/detection/attacks/. // // Tracks what was stripped so the trinary classifier can use // "normalization triggered" as a corroborating AI signal — humans don't // paste ZWSPs into their own writing. const CYRILLIC_LOOKALIKES = { 'а': 'a', 'е': 'e', 'о': 'o', 'р': 'p', 'с': 'c', 'х': 'x', 'у': 'y', 'к': 'k', 'м': 'm', 'н': 'h', 'в': 'b', 'т': 't', 'А': 'A', 'Е': 'E', 'О': 'O', 'Р': 'P', 'С': 'C', 'Х': 'X', 'У': 'Y', 'К': 'K', 'М': 'M', 'Н': 'H', 'В': 'B', 'Т': 'T', }; const GREEK_LOOKALIKES = { 'ο': 'o', 'Ο': 'O', 'α': 'a', 'Α': 'A', 'ρ': 'p', 'Ρ': 'P' }; // ─── Source-coordinate mapping (issue #189) ───────────────────────── // // Each entry maps one code unit in the working string to the matching // code unit in the caller's source. Deletion passes copy the entries for // retained characters once, so interleaved or overlapping removals cannot // double-count offsets. Masking and homoglyph replacement keep their input // length and therefore keep the current map unchanged. function identitySourceMap(length) { return Array.from({ length }, (_, index) => index); } function appendMapRange(target, source, start, end) { for (let index = start; index < end; index += 1) target.push(source[index]); } function remapFindingsToSource(issues, regions, sourceMap) { for (const issue of issues) { if (Number.isInteger(issue.index)) issue.index = sourceMap[issue.index]; } for (const region of regions) { region.start = sourceMap[region.start]; region.end = sourceMap[region.end - 1] + 1; } } const ZERO_WIDTH_RE = /[-]/u; const ZERO_WIDTH_GLOBAL_RE = /[-]/gu; const HOMOGLYPH_RE = /[Ѐ-ӿͰ-Ͽ]/u; const HOMOGLYPH_GLOBAL_RE = /[Ѐ-ӿͰ-Ͽ]/gu; const LATIN_LETTER_RE = /\p{Script=Latin}/u; // Dates, versions and ASCII filenames keep internal dots; prose may hard-wrap. // Other sentence punctuation and Markdown/HTML block starts separate units, even // without a space, so unrelated Russian text cannot hide an English word. const SENTENCE_UNIT_GLOBAL_RE = /(?:[^.!?\r\n]|(?<=[A-Za-z0-9_])\.(?=[A-Za-z0-9_])|\r?\n(?![ \t]*(?:\r?\n|(?:[-*+]|#{1,6}|\d+[.)])\s|[><|]|`{3}|~{3}|(?:(?:-+|=+)[\t ]*|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,}|(?:-[ \t]*){3,})(?:\r?\n|$)|:?-+:?[\t ]*(?:\|[\t ]*:?-+:?[\t ]*)+(?:\|[\t ]*)?(?:\r?\n|$))))+/g; // Words are letter runs; a hyphen splits them, so "API-сервис" stays two // words and its Russian half is not swapped. const LETTER_RUN_GLOBAL_RE = /[\p{L}\p{M}]+/gu; const ROLEPLAY_VERBS_RE = /^(?:nods|sighs|laughs|smiles|frowns|shrugs|grins|winks|chuckles|gasps|pauses|thinks|wonders|whispers|shouts|gestures|raises|leans|turns|looks|glances|smirks|blinks|nodding|sighing|laughing|smiling|thinking|gesturing)\b/i; const ROLEPLAY_MARKER_RE = /(?= 0 && i - before <= MAX_ZERO_WIDTH_SKIP && ZERO_WIDTH_RE.test(chars[before])) before -= 1; let after = i + 1; while (after < chars.length && after - i <= MAX_ZERO_WIDTH_SKIP && ZERO_WIDTH_RE.test(chars[after])) after += 1; // A two-unit slice lets the Unicode regex see a supplementary-plane letter. return LETTER_END_RE.test(chars.slice(Math.max(0, before - 1), before + 1)) && LETTER_START_RE.test(chars.slice(after, after + 2)); } function normalizeText(text, sourceMap) { const flags = { zeroWidth: 0, homoglyph: 0, roleplay: 0 }; let out = text; let map = Array.isArray(sourceMap) ? sourceMap : null; // 1. Strip zero-width chars (ZWSP U+200B, ZWNJ U+200C, ZWJ U+200D, // BOM U+FEFF, word joiner U+2060). Word joiners outside a word are // stripped without being counted; see countsAsBypass. if (map) { const chars = []; const nextMap = []; for (let i = 0; i < out.length; i += 1) { if (ZERO_WIDTH_RE.test(out[i])) { if (countsAsBypass(out, i)) flags.zeroWidth += 1; continue; } chars.push(out[i]); nextMap.push(map[i]); } out = chars.join(''); map = nextMap; } else { out = out.replace(ZERO_WIDTH_GLOBAL_RE, (_, offset, whole) => { if (countsAsBypass(whole, offset)) flags.zeroWidth += 1; return ''; }); } // 2. Swap Cyrillic / Greek Latin-lookalike chars back to Latin so // pattern matching catches obfuscated tokens. Swapping every а, е, о // reported thousands of "homoglyph swaps" on plain Russian text, and // swapping inside ordinary Russian words flagged bilingual technical // text, so only two word shapes are swapped: // - mixed-script words ("pаypal", "dеlve"), anywhere; // - words of two or more letters spelled entirely in lookalike // letters ("аст" for "act"), when the sentence around them has no // Russian or Greek in it: every Cyrillic and Greek letter in the // sentence is a lookalike. Deciding per sentence, not per document, // keeps Russian padding from hiding such a word in an English // sentence. // Sentence punctuation, blank lines and Markdown block starts separate units. // Internal ASCII-token dots ("07.10", "v1.2", "report.pdf") and a prose // hard wrap do not end it: cutting there left pieces such as "поста в // r/StableDiffusion от 07" that looked like Latin text. // Ordinary Russian words contain non-lookalike letters (з, п, и, л), // so short Russian words in Russian technical prose ("на Enum", // "от 07.10") stay put, and one-letter prepositions (с, о, у) are too // short. // Known limits, because no letter-level rule separates these from // real Russian: a fully substituted word inside or next to Russian // words ("МЕТА поможет", "пароль: аст"), including across prose hard wraps, // is left alone; a one-letter // lookalike split off by a hyphen ("а-ct") is left alone; and a short // Russian sentence spelled only in lookalike letters ("Он сам.") is // swapped. const lookalikeFor = (m) => CYRILLIC_LOOKALIKES[m] ?? GREEK_LOOKALIKES[m]; const swapLookalike = (m) => { const swap = lookalikeFor(m); if (swap) { flags.homoglyph++; return swap; } return m; }; const letterCount = (word) => (word.match(/\p{L}/gu) || []).length; const allLookalike = (word) => letterCount(word) >= 2 && [...word].every((ch) => lookalikeFor(ch) || !/\p{L}/u.test(ch)); out = out.replace(SENTENCE_UNIT_GLOBAL_RE, (unit) => { const scriptLetters = unit.match(HOMOGLYPH_GLOBAL_RE) || []; const onlyLookalikes = scriptLetters.length > 0 && scriptLetters.every((ch) => lookalikeFor(ch)); const words = [...unit.matchAll(LETTER_RUN_GLOBAL_RE)]; let result = ''; let last = 0; words.forEach((match) => { const word = match[0]; let next = word; if (HOMOGLYPH_RE.test(word)) { if (LATIN_LETTER_RE.test(word) || (allLookalike(word) && onlyLookalikes)) { next = word.replace(HOMOGLYPH_GLOBAL_RE, swapLookalike); } } result += unit.slice(last, match.index) + next; last = match.index + word.length; }); return result + unit.slice(last); }); // 3. Strip *roleplay-action* markers — paired *...* containing an // action verb (nods, sighs, laughs, smiles, etc.) anchored to // the start of the inner phrase. This is the actual chat-model // artifact shape. Markdown `**bold**` is rejected by the // lookbehind/lookahead; legitimate multi-word `*italic*` is // preserved because the verb whitelist is narrow. if (map) { const chars = []; const nextMap = []; const matcher = new RegExp(ROLEPLAY_MARKER_RE.source, ROLEPLAY_MARKER_RE.flags); let cursor = 0; let match; while ((match = matcher.exec(out)) !== null) { if (!ROLEPLAY_VERBS_RE.test(match[1])) continue; chars.push(out.slice(cursor, match.index)); appendMapRange(nextMap, map, cursor, match.index); flags.roleplay += 1; cursor = match.index + match[0].length; } chars.push(out.slice(cursor)); appendMapRange(nextMap, map, cursor, map.length); out = chars.join(''); map = nextMap; } else { out = out.replace(ROLEPLAY_MARKER_RE, (m, inner) => { if (ROLEPLAY_VERBS_RE.test(inner)) { flags.roleplay += 1; return ''; } return m; }); } return map ? { text: out, flags, sourceMap: map } : { text: out, flags }; } // Terms with legitimate technical meaning that are suppressed when contextMode === 'technical'. // See references/patterns.md and issue #237. const TECHNICAL_EXEMPT = new Set([ 'robust', 'comprehensive', 'seamless', 'seamlessly', 'ecosystem', 'leverage', 'leverages', 'leveraging', 'leveraged', 'facilitate', 'facilitates', 'underpin', 'underpinning', 'underpinnings', 'streamline', ]); // ─── Tier 1: Always flag ─────────────────────────────────────────── const TIER1 = { 'delve': 'explore, dig into, look at', 'tapestry': 'complex structure, rich history', 'paradigm': 'model, approach, framework', 'beacon': 'rewrite entirely', 'robust': 'strong, reliable, solid', 'comprehensive': 'thorough, complete, full', 'cutting-edge': 'latest, newest, advanced', 'pivotal': 'important, key, critical', 'meticulous': 'careful, detailed, precise', 'meticulously': 'carefully, precisely', 'seamless': 'smooth, easy, without friction', 'seamlessly': 'smoothly, easily', 'game-changer': 'changes how [X] works', 'game-changing': 'changes how [X] works', 'nestled': 'is located, sits', 'vibrant': 'lively, active', 'thriving': 'growing, active', 'bustling': 'busy, active', 'intricate': 'complex, detailed', 'intricacies': 'complexities, details', 'ever-evolving': 'changing, growing', 'enduring': 'lasting, long-running', 'daunting': 'hard, difficult', 'holistic': 'complete, full, whole', 'holistically': 'completely, fully', 'actionable': 'practical, useful, concrete', 'impactful': 'effective, significant', 'learnings': 'lessons, findings, takeaways', 'synergy': 'combined effect, benefit of working together', 'synergies': 'combined effect, benefit of working together', 'interplay': 'relationship, connection', 'symphony': 'coordination, balance', 'embrace': 'adopt, accept, use', }; // Multi-word tier 1 phrases // "features" is copula avoidance only as a verb: "the app features a // dashboard". The plural noun ("three new features", a "Features" heading, // "the features we shipped") is ordinary product and technical writing, and // it is most of what the word does in corpus/ (#351). A verb needs a subject // before it and an object after it, so the word counts as a noun when it // opens a sentence, line or list item; follows a determiner, number, // possessive, quantifier, "of", "or" or a compound modifier; or comes // before punctuation, a line break, a preposition, a conjunction, a pronoun // or a verb. // Singular "this", "that" and "each" cannot determine the plural noun: // here they are subjects ("each features a...") or a relative pronoun. const FEATURES_NOUN_BEFORE_RE = /(?:^|[.!?:;(]\s*|(?:^|\n)[ \t]*(?:[-*+>#]+[ \t]*)?|\b(?:the|a|an|these|those|its|their|our|your|my|his|her|of|or|new|key|main|core|top|other|more|most|many|several|some|all|any|few|no|both|only|about|over|just|free|similar|common|specific|distinct|additional|extra|premium|advanced|basic|best|unique|missing|upcoming|existing|latest|major|minor|useful|important|various|different|certain|such|\d+|two|three|four|five|six|seven|eight|nine|ten|whose)\s+|\w['’]s\s+|\w[-/]\w+\s+)$/i; // "on-device" is an object modifier, not the preposition "on". const FEATURES_NOUN_AFTER_RE = /^(?:[ \t]*(?:[.,;:!?()[\]"'’”\n]|$)|\s+(?:of|for|in|on|at|into|and|or|but|nor|are|were|is|was|be|been|being|that|which|who|whose|like|such|to|from|with|without|than|help|helps|helped|let|allow|make|keep|give|provide|enable|offer|save|protect|ensure|improve|reduce|support|remain|vary|need|unlock|bring|include|includes|included|work|works|worked|will|can|could|should|would|may|might|must|do|did|does|have|has|had|we|you|they|i|it)(?![\w-]))/i; // Bare product objects: "we ship features", "teams build features". // A subject is required so noun subjects such as "the ship"/"the build" // still flag. One optional modifier preserves "we ship GPT-5 features". const FEATURES_NOUN_OBJECT_RE = /\b(?:i|we|you|they|teams?|developers?|engineers?|users?|companies|vendors|the\s+(?:release|update))\s+(?:(?:can|could|will|would|should|must)\s+)?(?:ship|ships|shipped|shipping|build|builds|built|building|add|adds|added|adding)\s+(?:[\w./-]+\s+)?$/i; // Leads that make "which/what features" an indirect question (#384): a question // verb that opens its clause ("Decide which...", "we should check which..."), // or which/what at the start of a sentence or list item. A lead word inside a // noun phrase ("a security check which features...") does not count. const FEATURES_QUESTION_LEAD_RE = /(?:^|[.!?:;]\s*|(?:^|\n)[ \t]*(?:[-*+>#]+[ \t]*)?|(?:^|[.!?:;,]\s*|(?:^|\n)[ \t]*(?:[-*+>#]+[ \t]*)?|\b(?:i|we|you|they|he|she|let['’]?s|to|can|could|should|must|will|would|please|just|then|first|now|and|or|but|so)\s+)(?:decide|decides|deciding|choose|choosing|pick|check|checking|see|know|knowing|learn|find\s+out|figure\s+out|work\s+out|identify|determine|ask|asking|asked|tell\s+(?:me|us|them|you)|show\s+(?:me|us|them|you)|understand|explain|wonder|discover|confirm|consider|evaluate|prioritize|about)\s+)(?:which|what)\s+$/i; // A lead word after a determiner is a noun ("a track which features...", // "the review which features..."), not a question verb. const FEATURES_LEAD_AS_NOUN_RE = /\b(?:a|an|the|this|that|these|those|my|our|your|their|its|his|her|each|every)\s+[\w-]+\s+(?:which|what)\s+$/i; // Subjects that definitively make "features" a verb, avoiding ambiguity with // plural-noun subjects like "The experimental features" or "Security features". const FEATURES_VERB_SUBJECTS = /\b(?:library|tool|app|application|platform|system|language|service|product|update|release|version|site|website|game|device|model|framework|package|plugin|extension|which|what|that|who|it|he|she)\s+$/i; function featuresIsNoun(text, index) { const end = index + 'features'.length; const before = text.slice(Math.max(0, index - 40), index); const after = text.slice(end, end + 40); if (FEATURES_NOUN_OBJECT_RE.test(before)) return true; // A recognizable model/version followed by an object article is a // subject: "GPT-5 features a...", "Windows 11 features a...". // Determiner-led counts ("These 3 features a customer requested") and // the explicit object contexts above remain nouns. This is a bounded // context heuristic, not a grammatical parse of every use of the word. const product = /\b([A-Z][\w]*)(?:[-/]\d[\w.-]*|[ \t]+\d+(?:\.\d+)*)[ \t]+$/.exec(before); if (product && !FEATURES_NOUN_BEFORE_RE.test(`${product[1]} `) && /^\s+(?:a|an|the)(?![\w-])/i.test(after)) return false; // A short comma-delimited aside can precede the verb's article-led // object. Strong noun contexts still take priority over punctuation. if (!FEATURES_NOUN_BEFORE_RE.test(before) && /^[ \t]*,[^,\n]{1,80},\s*(?:a|an|the)(?![\w-])/i.test(text.slice(end, end + 110))) return false; // "which/what features" is a noun in an indirect question: right after a // question verb ("Decide which features matter") or at the start of a // sentence ("Which features matter most..."). Every other context falls // through to the checks below unchanged, so relative clauses ("a library // which features dashboards") keep their verb finding (#384). if (FEATURES_QUESTION_LEAD_RE.test(before) && !FEATURES_LEAD_AS_NOUN_RE.test(before)) { // If there is no trailing verb (e.g. end of clause), it's the verb case ("Check what features a dashboard and export tools."). // Look past a compound subject and optional appositive for a trailing verb before returning the verb classification. const match = /^\s+(?:a|an|the)\s+[\w-]+\s*(?:(?:and\b|or\b)\s+(?:a\s+|an\s+|the\s+)?(?:[\w-]+\s+){0,2}[\w-]+\s*)?(?:([,.!?;])|$)/i.exec(after); if (match) { const predicateRe = /\b(?:can|could|should|will|would|may|might|must|is|are|was|were|has|have|had|do|does|did|include|includes|disable|disables|reject|accept|allow|deny|provide|require|use|make|work|help|give|take|need|become|seem|look|show|offer|support|supports|fail|pass|lack|prefer|choose|prevent|stop)\b/i; // If the matched subject ends with a predicate right before the punctuation, // the predicate was consumed as part of the compound subject. const subjectText = match[0].slice(0, match[1] ? -match[1].length : undefined).trim(); const lastWord = subjectText.split(/\s+/).pop(); if (predicateRe.test(lastWord)) { return true; } if (match[1] === ',') { // If the comma leads into a phrase, limit noun classification to a predicate // belonging to the article-led subject (after the next comma), excluding predicates inside subordinate clauses. const remainder = text.slice(end + match[0].length, end + 120); // An adverb can sit between the closing comma and the predicate. const remainderPredicateRe = new RegExp(`^[^,]+,\\s*(?:(?:[\\w-]+ly|also|not|never)\\s+){0,2}${predicateRe.source}`, 'i'); if (remainderPredicateRe.test(remainder)) { return true; } } return false; } return true; } // "The library features support for..." is a verb. // "Security features support for..." is a plural noun subject + verb. if (FEATURES_VERB_SUBJECTS.test(before) && /^\s+support\s+for\b/i.test(after)) { // A nearby quantifier in an earlier clause cannot make a singular pronoun plural. if (/\b(?:it|he|she)\s+$/i.test(before)) return false; const hasPluralDeterminer = /\b(?:these|those|all|some|many|few|various|multiple|several|both)\s+(?:[\w-]+\s+){1,2}$/i.test(before); // Count words modify "features" only when they follow its determiner. // A digit inside a product name ("This Windows 11 app") or a date before // the subject ("In 2024 the library") is not a plural count. const hasPluralCount = /\b(?:the|a|an|this|that|my|our|your|their|its|his|her|each|every)\s+(?:(?:\d{1,2}|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|dozen)\s+(?:[\w-]+\s+){1,2}|(?!(?:19|20)\d{2}\s)\d{3,}\s+(?!(?:[\w-]+\s+)?(?:app|release|model|version|update)\s+$)(?:[\w-]+\s+){1,2})$/i.test(before); const extendedAfter = text.slice(end, end + 100); // A predicate inside a relative clause modifying the object (e.g. "teams that connect and remain online") // is not coordinated with the main subject. Limit predicate search to the direct prepositional object. const hasPartitivePlural = /\b(?:all|some|many|most|few|several|both|\d+|two|three|four|five|six|seven|eight|nine|ten)\s+of\s+(?:the|my|our|your|their|its|his|her)\s+(?:[\w-]+\s+){1,3}$/i.test(before); const hasPluralPredicate = /^\s+support\s+for(?:(?!\b(?:that|which|who|whom|whose|where|when)\b)[^.?!;]){0,80}?\b(?:and|but|or|nor)\s+(?:are|were|have|do|reject|accept|allow|deny|provide|require|use|make|work|help|give|take|need|become|seem|look|show|include|offer|support|remain|fail|pass|lack|prefer|choose|prevent|stop)\b/i.test(extendedAfter); const hasForObject = /^\s+support\s+for(?:-|\s+)(?:profit|loops?)\b/i.test(after); // Numeric modifiers and plural cues exclude a singular-subject reading: // "The two platform features..." has plural noun "features". // Do not borrow a determiner across a preposition or conjunction: // "a suite of system features" still has plural noun "features". // "that" can introduce a clause and "which" can determine plural nouns. // A relative pronoun needs its own determiner-led subject evidence. const hasUnambiguousSingular = /\b(?:a|an|this|that|every|each|one)\s+(?:(?!(?:of|for|in|with|and|or|which|what|that|who|two|three|four|five|six|seven|eight|nine|ten|multiple|several|many|few|both|various)\b)[\w-]+\s+){1,3}$/i.test(before) || /\b(?:it|he|she)\s+$/i.test(before) || /\b(?:a|an|this|that|each|every|one)\s+[\w-]+\s+(?:which|that|who)\s+$/i.test(before); const hasSingularEvidence = hasUnambiguousSingular || /\b(?:the|my|our|your|their|its|his|her)\s+(?:(?!(?:of|for|in|with|and|or|which|what|that|who|two|three|four|five|six|seven|eight|nine|ten|multiple|several|many|few|both|various)\b)[\w-]+\s+){1,3}$/i.test(before) || /\b(?:the|my|our|your|their|its|his|her)\s+[\w-]+\s+(?:which|that|who)\s+$/i.test(before); // Unambiguous singular subjects ("It", "This app") cannot be plural-noun phrases, // so hasForObject ("support for loops") only suppresses ambiguous determiners ("The library"). if (!hasPluralDeterminer && !hasPluralCount && !hasPartitivePlural && !hasPluralPredicate && (hasUnambiguousSingular || (!hasForObject && hasSingularEvidence))) { return false; } } return FEATURES_NOUN_BEFORE_RE.test(before) || FEATURES_NOUN_AFTER_RE.test(after); } const TIER1_PHRASES = [ { pattern: /\bdelve\s+into\b/gi, replace: 'explore, dig into' }, { pattern: /\blandscape\b/gi, replace: 'field, space, industry', filter: true }, { pattern: /\brealm\b/gi, replace: 'area, field, domain' }, { pattern: /\btestament\s+to\b/gi, replace: 'shows, proves' }, { pattern: /\bleverag(?:e|es|ing|ed)\b/gi, replace: 'use' }, { pattern: /\bwatershed\s+moment\b/gi, replace: 'turning point, shift' }, { pattern: /\bmarking\s+a\s+pivotal\s+moment\b/gi, replace: 'changing [X], leading to [Y]' }, { pattern: /\bthe\s+future\s+looks\s+bright\b/gi, replace: 'cut or say something specific' }, { pattern: /\bonly\s+time\s+will\s+tell\b/gi, replace: 'cut or say something specific' }, { pattern: /\bdespite\s+challenges[^.]*continues?\s+to\s+thrive\b/gi, replace: 'keeps growing despite [named difficulty], continues to succeed despite [named difficulty]' }, { pattern: /\bdeep\s+dive\b/gi, replace: 'look at, examine' }, { pattern: /\bdive\s+into\b/gi, replace: 'look at, examine' }, { pattern: /\bunpack(?:ing)?\b/gi, replace: 'explain, break down' }, { pattern: /\bcomplexities\b/gi, replace: 'problems, details' }, { pattern: /\bthought\s+leader(?:ship)?\b/gi, replace: 'expert, authority' }, { pattern: /\bbest\s+practices\b/gi, replace: 'what works, proven methods' }, { pattern: /\bat\s+its\s+core\b/gi, replace: 'cut, just state it' }, { pattern: /\bin\s+order\s+to\b/gi, replace: 'to', clarity: true }, { pattern: /\bdue\s+to\s+the\s+fact\s+that\b/gi, replace: 'because', clarity: true }, { pattern: /\bserves\s+as\b/gi, replace: 'is', clarity: true }, { pattern: /\bfeatures\b/gi, replace: 'has, includes', filter: true, clarity: true, skip: featuresIsNoun }, { pattern: /\bboasts\b/gi, replace: 'has', clarity: true }, { pattern: /\butiliz(?:e|es|ing|ed)\b/gi, replace: 'use', clarity: true }, { pattern: /\bshowcas(?:e|es|ing|ed)\b/gi, replace: 'show, demonstrate' }, { pattern: /\bembark(?:s|ing|ed)?\b/gi, replace: 'start, begin' }, { pattern: /\bcommenc(?:e|es|ing|ed)\b/gi, replace: 'start, begin', clarity: true }, { pattern: /\bascertain(?:s|ing|ed)?\b/gi, replace: 'find out, determine', clarity: true }, { pattern: /\bendeavou?r(?:s|ing|ed)?\b/gi, replace: 'effort, attempt, try', clarity: true }, { pattern: /\bunderscor(?:es|ing|ed)\b/gi, replace: 'highlights, shows' }, // Hyphen required. The unhyphenated "load bearing" is ordinary English — // "the load bearing down on the bridge" — where `bearing` is a participle, // not part of a compound modifier. The tell is always hyphenated. // // Only match an immediately following abstract noun from this seed list. // Unknown nouns, mixed physical/abstract nouns, and predicative uses pass: // precision over recall (#56). Keep the lookahead out of the matched span. { pattern: /\bload-bearing\b(?=[ \t]+(?:assumptions?|claims?|invariants?|premises?|constraints?|dependenc(?:y|ies)|arguments?|abstractions?)\b)/gi, replace: 'essential, critical, or say what breaks if you remove it' }, ]; // ─── Tier 2: Flag in clusters (2+ per paragraph) ────────────────── const TIER2 = { 'harness': 'use, take advantage of', 'navigate': 'work through, handle', 'navigating': 'working through, handling', 'foster': 'encourage, support, build', 'elevate': 'improve, raise, strengthen', 'unleash': 'release, enable, unlock', 'streamline': 'simplify, speed up', 'empower': 'enable, let, allow', 'bolster': 'support, strengthen', 'spearhead': 'lead, drive, run', 'resonate': 'connect with, appeal to', 'resonates': 'connects with, appeals to', 'revolutionize': 'change, transform', 'facilitate': 'enable, help, allow', 'facilitates': 'enables, helps, allows', 'underpin': 'support, form the basis of', 'nuanced': 'specific, subtle, detailed', 'crucial': 'important, key, necessary', 'multifaceted': 'having several parts, with several aspects', 'ecosystem': 'system, community, network', 'myriad': 'many, numerous', 'plethora': 'many, a lot of', 'encompass': 'include, cover, span', 'catalyze': 'start, trigger, accelerate', 'reimagine': 'rethink, redesign, rebuild', 'galvanize': 'motivate, rally, push', 'augment': 'add to, expand, supplement', 'cultivate': 'build, develop, grow', 'illuminate': 'clarify, explain, show', 'elucidate': 'explain, clarify', 'juxtapose': 'compare, contrast', 'transformative': 'changes how [X] works', 'transformation': 'major change, overhaul', 'cornerstone': 'foundation, basis, key part', 'paramount': 'most important, top priority', 'poised': 'ready, set, about to', 'burgeoning': 'growing, emerging', 'nascent': 'new, early-stage', 'quintessential': 'typical, classic, defining', 'overarching': 'main, central, broad', 'quietly': 'cut, or name the concrete contrast', 'underpinning': 'basis, foundation', 'underpinnings': 'basis, foundations', 'paradigm-shifting': 'changes the basic model, changes how [X] is understood', }; // Conditional Tier 2 entries: everyday words whose AI tell is a specific // significance collocation, not the word itself. They join a paragraph's // Tier 2 cluster only when the collocation matches — bare uses ("deeply // nested JSON", "cares deeply") never count, because the base rate of // these words in innocent prose is far higher than the rest of the table // and an unconditional entry measurably flags clean human writing. const TIER2_CONDITIONAL = [ { word: 'deeply', pattern: /\bdeeply\s+(?:integrated|committed|rooted|personal|human|flawed|resonant|transformative|interconnected|ingrained|embedded|meaningful)\b/i, suggestion: 'cut, or name what specifically runs deep', }, ]; // ─── Tier 3: Flag by density ─────────────────────────────────────── const TIER3 = [ 'significant', 'significantly', 'innovative', 'innovation', 'effective', 'effectively', 'dynamic', 'dynamics', 'scalable', 'scalability', 'compelling', 'unprecedented', 'exceptional', 'exceptionally', 'remarkable', 'remarkably', 'sophisticated', 'instrumental', 'world-class', 'state-of-the-art', 'best-in-class', // `verbatim` is usually redundant with the verb it modifies ("copies X // verbatim" = "copies X"). It has a genuine term-of-art sense in legal, // research, and QA registers ("verbatim transcript"), so it lives at Tier 3: // density-gated, it only fires on overuse, not on a single legitimate use. 'verbatim', ]; // Multi-word Tier 3 phrases. Density-gated like single Tier 3 words because // these legitimately show up in human crypto/web3/dev writing. Threshold is // intentionally lower than single-word Tier 3 (≥2 occurrences of the same // phrase) — repeating the same multi-word boilerplate is a stronger AI tell // than re-using "significant." const TIER3_PHRASES = [ /\bemerging\s+(?:sector|space|category|industry)\b/gi, /\bthe\s+integration\s+of\b/gi, /\bthe\s+intersection\s+of\b/gi, /\bcommunity-?driven\b/gi, /\blong-?term\s+sustainability\b/gi, /\buser\s+engagement\b/gi, /\bdecentralized\s+compute\b/gi, /\b(?:sustainable\s+)?reward\s+emissions?\b/gi, /\btokenized\s+incentive\s+structures?\b/gi, /\bdesigned\s+for\s+long-?term\b/gi, ]; // O(1) lookup from any token form (hyphenated or dashless) to its canonical // Tier 3 word. Counting originally did nested-loop word matching which was // O(tokens × TIER3) — slow on long pastes. const TIER3_LOOKUP = new Map(); for (const word of TIER3) { TIER3_LOOKUP.set(word, word); const dashless = word.replace(/-/g, ''); if (dashless !== word) TIER3_LOOKUP.set(dashless, word); } // Per-category score weights. Applied to distinct (deduplicated) issues so // the score reflects the same signals the user sees in the issue list. // Non-uniform on purpose: critical rules like cutoff disclaimers (×10) and // chatbot artifacts (×8) weigh more than vague attributions (×5), even // though all three are tagged `critical`. const ISSUE_WEIGHTS = { tier1: 5, // Wordiness, not an AI-frequency marker. Weighted like tier2 so a // clarity fix cannot push a document toward an AI classification. 'tier1-clarity': 3, tier2: 3, tier3: 2, transition: 2, chatbot: 8, sycophantic: 8, filler: 2, 'generic-conclusion': 3, 'lets-construction': 2, 'reasoning-artifact': 6, 'significance-inflation': 4, 'vague-attribution': 5, 'hollow-intensifier': 2, // Issue #82 evidence boundary: this style pattern produced no detector hits // in either corpus class, so it has no measured authorship direction. Keep // the finding visible, but do not move authorship scores or probabilities // until a relevant positive evaluation set supports a direction. 'emotional-flatline': 0, 'lingering-attention': 3, 'novelty-inflation': 3, 'cutoff-disclaimer': 10, 'template-phrase': 3, 'false-concession': 2, 'rhetorical-question': 2, 'confidence-calibration': 2, // Writing-quality guidance whose authorship polarity changes across model // generations. Keep the flag visible without moving authorship outputs. 'em-dash': 0, uniformity: 5, formatting: 3, 'tier3-phrase': 3, // Structural / cluster signals are deliberately weighted high. Unlike // single-vocabulary hits they're near-dispositive on social-length // posts (a 15-hashtag block, a 6-item bullet-NP list, three distinct // crypto-shill phrases stacked) and would otherwise be suppressed by // the log2(words/50) length divisor on short pastes. 'tier3-phrase-cluster': 12, 'hashtag-stuff': 12, 'bullet-np-list': 10, 'hedge-stack': 6, 'future-narrative': 12, 'real-actual-inflation': 5, // Social endorsement / CTA closer. Weighted like formulaic-opener: a // strong single-hit social tell that the length divisor would // otherwise wash out on a short LinkedIn-length post. 'social-cta-closer': 8, // Performed-insight tics: single hits are common in human essays, so // weighted like tier2 vocabulary — density does the classifying. 'performed-insight': 3, // Negation chains are a strong single-hit structural tell. 'negation-chain': 5, // Negative parallelism ("It's not just X, it's Y"). The frame is also // how people state a real correction, so it is weighted below the // negation chain; the per-piece gate in analyzeText does the rest. 'negative-parallelism': 4, 'dev-blog-boilerplate': 3, 'formulaic-opener': 8, // Speculative scenario opener ("Imagine a world where…"). Weighted like // formulaic-opener: a single strong opener tell the length divisor would // otherwise wash out on a short post. 'speculative-opener': 8, // Launch-copy introduction ("Enter X.", "Meet X, your new..."). // Weighted like the other single-hit opener tells: strong on the // short launch posts where it actually appears. 'launch-intro': 8, // Dramatized crowd contrast. Gated hard on the dismissive verb, so // a hit is meaningful, but the surface shares words with ordinary // narrative — weighted below the opener tells on purpose. 'crowd-contrast': 6, // Fake-casual props (stage directions, wink asides). Near-costume // when present; same class as the opener tells on short posts. 'fake-casual-prop': 8, 'title-case-header': 4, 'parenthetical-hedge': 3, // House-style typography is a style review prompt, not authorship // evidence. Keep it neutral in both the score and classifier (#351). 'smart-punct-signature': 0, 'punct-distribution': 6, 'fnword-trigram-entropy': 5, 'cross-para-burstiness': 5, 'normalization-flag': 9, // Vocabulary-diversity signal (type-token ratio). Weighted modestly // because the threshold (>=200 tokens AND TTR<0.4) is conservative; // it stacks with structural signals to push borderline scores up. 'low-ttr': 3, // AI-tool fingerprints. Weighted higher than statistical patterns // because each is a near-definitive single-hit signal — the AI tool // literally left its mark in the text. citation-markup ranks highest // (smoking gun: the literal internal markup of ChatGPT/Grok/etc.), // UTM tracking second (auto-appended by the tool to URLs it writes), // placeholders third (strong but humans use bracketed slots in // templates legitimately and forget them — still a publishing bug // but slightly less definitive AI evidence). 'ai-placeholder': 10, 'ai-citation-markup': 15, 'ai-utm-source': 12, // Curated P2 copyedits, not authorship evidence. Keep them visible in the // issue list without moving the AI score, label, probabilities, or // trinary classification on short documents. 'unnecessary-hyphenation': 0, }; // ─── Transition phrases ──────────────────────────────────────────── const TRANSITIONS = [ /\bmoreover\b/gi, /\bfurthermore\b/gi, /\badditionally\b/gi, /\bin\s+today'?s\b/gi, /\bin\s+an\s+era\s+where\b/gi, /\bit'?s\s+worth\s+noting\s+that\b/gi, /\bnotably\b/gi, /\bin\s+conclusion\b/gi, /\bin\s+summary\b/gi, /\bto\s+summarize\b/gi, /\bwhen\s+it\s+comes\s+to\b/gi, /\bat\s+the\s+end\s+of\s+the\s+day\b/gi, /\bthat\s+(?:being\s+)?said\b/gi, ]; // ─── Chatbot artifacts ───────────────────────────────────────────── const CHATBOT_ARTIFACTS = [ /\bi\s+hope\s+this\s+helps\b/gi, /\bcertainly!\b/gi, /\babsolutely!\b/gi, /\bgreat\s+question!\b/gi, /\bexcellent\s+point!\b/gi, /\bfeel\s+free\s+to\s+reach\s+out\b/gi, /\blet\s+me\s+know\s+if\s+you\s+need\s+anything\b/gi, /\bin\s+this\s+article,?\s+we\s+will\s+explore\b/gi, /\blet'?s\s+dive\s+in!?\b/gi, ]; // ─── Sycophantic tone ────────────────────────────────────────────── const SYCOPHANTIC = [ /\byou'?re\s+absolutely\s+right\b/gi, /\bthat'?s\s+a\s+really\s+insightful\b/gi, /\bthat'?s\s+a\s+great\s+question\b/gi, /\bexcellent\s+question\b/gi, ]; // ─── Filler phrases ──────────────────────────────────────────────── const FILLERS = [ /\bit\s+is\s+important\s+to\s+note\s+that\b/gi, /\bin\s+terms\s+of\b/gi, /\bthe\s+reality\s+is\s+that\b/gi, /\bit'?s\s+important\s+to\s+note\s+that\b/gi, ]; // ─── Generic conclusions ─────────────────────────────────────────── const GENERIC_CONCLUSIONS = [ /\bthe\s+future\s+looks\s+bright\b/gi, /\bonly\s+time\s+will\s+tell\b/gi, /\bone\s+thing\s+is\s+certain\b/gi, /\bas\s+we\s+move\s+forward\b/gi, ]; // ─── "Let's" constructions ───────────────────────────────────────── const LETS_PATTERNS = [ /\blet'?s\s+explore\b/gi, /\blet'?s\s+take\s+a\s+look\b/gi, /\blet'?s\s+break\s+this\s+down\b/gi, /\blet'?s\s+examine\b/gi, /\blet'?s\s+(?:consider|discuss|delve|unpack|walk\s+through)\b/gi, ]; // ─── Reasoning chain artifacts ───────────────────────────────────── const REASONING_ARTIFACTS = [ /\blet\s+me\s+think\s+step\s+by\s+step\b/gi, /\bbreaking\s+this\s+down\b/gi, /\bto\s+approach\s+this\s+systematically\b/gi, /\bhere'?s\s+my\s+thought\s+process\b/gi, /\bfirst,?\s+let'?s\s+consider\b/gi, /\bworking\s+through\s+this\s+logically\b/gi, ]; // NOTE: Acknowledgment loops are judgment-only (#239). The three phrases the // detector matched ("you're asking about", "the question of whether", "to answer // your question") are also how people open an ordinary reply and standard // analytical English. The tell is a restatement that adds nothing, which a // regex cannot see. See detector/CATEGORIES.md §C. // ─── Significance inflation ──────────────────────────────────────── const SIGNIFICANCE_INFLATION = [ /\bmarking\s+a\s+(?:pivotal|significant|important)\s+moment\b/gi, /\ba\s+watershed\s+moment\s+for\b/gi, // Require an inflating word before "in the evolution of" (the bare phrase // is allowed for literal uses like "a key stage in the evolution of the // vertebrate eye"). See issue #212. /\b(?:moment|milestone|chapter|era|turning\s+point|watershed|inflection\s+point|leap|role|new\s+phase)\s+in\s+the\s+evolution\s+of\b/gi, /\ba\s+(?:pivotal|defining)\s+moment\s+in\b/gi, ]; // ─── Vague attributions ──────────────────────────────────────────── const VAGUE_ATTRIBUTIONS = [ /\bexperts\s+(?:believe|say|suggest|agree)\b/gi, /\bstudies\s+(?:show|suggest|indicate)\b/gi, /\bresearch\s+(?:shows|suggests|indicates)\b/gi, /\bindustry\s+leaders\s+(?:agree|believe|say)\b/gi, ]; // ─── Hollow intensifiers ────────────────────────────────────────── const HOLLOW_INTENSIFIERS = [ /\bgenuine(?:ly)?\b/gi, /\btruly\b/gi, /\bquite\s+frankly\b/gi, /\bto\s+be\s+honest\b/gi, /\blet'?s\s+be\s+clear\b/gi, ]; // ─── Emotional flatline ──────────────────────────────────────────── // The "interesting (part|thing|aspect|piece)" family is matched in two // shapes: (1) "the most interesting X" inline (the canonical AI list // intro), and (2) bare "Interesting X:" used as a section-header opener, // which is the section-break variant that slipped past v3.3.x. const EMOTIONAL_FLATLINE = [ /\bwhat\s+surprised\s+me\s+most\b/gi, /\bi\s+was\s+fascinated\s+to\b/gi, /\bwhat\s+struck\s+me\s+was\b/gi, /\bi\s+was\s+excited\s+to\s+learn\b/gi, /\bthe\s+most\s+interesting\s+(?:part|thing|aspect|piece)\b/gi, // Multiline flag (/m) so `^` matches at every line start, including // position 0 of a pasted text that has no leading newline. The earlier // `(?:^|\n)` form silently missed bare openers at the very start of // input — caught by silent-failure audit 2026-05-16. Leading whitespace // is `[ \t]*`, not `\s*`: with /m every line start is a match attempt, // and a `\s*` that can cross newlines rescans the whole blank run from // each of them, which made a long masked block quadratic (#235). /^[ \t]*interesting\s+(?:part|thing|aspect|piece)(?:\s+of\s+(?:the\s+)?\w+)?\s*:/gim, ]; // ─── Lingering-attention claims ──────────────────────────────────── // The share-post opener that claims duration of attention instead of // saying anything about the thing ("the line I keep coming back to"). // // Precision note: the bare verb phrase "I keep coming back to X" is NOT // matched on its own, because it is legitimate whenever a reason follows // ("I keep coming back to Hirschman because it predicts who quits"), and // the reason clause is not reliably detectable by regex. Only the // noun-anchored frame ("the line/quote/bit ... I keep coming back to") // fires, which is the shape that introduces a subject rather than // asserting something about it. The bare form stays a skill-prose // judgment call. See SKILL.md §Lingering-attention claims carve-out. const LINGERING_ATTENTION = [ // "the line I keep coming back to", "the one quote that I keep coming back to" // Noun-anchored frame only. "can't stop thinking about" is deliberately // left to its own pattern below rather than folded into this alternation, // so "the line I can't stop thinking about" scores once, not twice. /\b(?:the|that|this)\s+(?:one\s+)?(?:line|quote|bit|part|idea|point|framing|comment|thing)\s+(?:that\s+)?i\s+keep\s+(?:coming\s+back\s+to|thinking\s+about)\b/gi, /\bi\s+can'?t\s+stop\s+thinking\s+about\b/gi, /\bstill\s+thinking\s+about\s+(?:this|that)\s+one\b/gi, /\b(?:been|be)\s+rattling\s+around\s+(?:in\s+)?my\s+(?:head|brain)\b/gi, /\bi'?ve\s+been\s+chewing\s+on\s+(?:this|that)\b/gi, ]; // ─── Novelty inflation ───────────────────────────────────────────── const NOVELTY_INFLATION = [ /\bthe\s+failure\s+mode\s+nobody'?s?\s+naming\b/gi, /\ba\s+problem\s+nobody\s+talks\s+about\b/gi, /\bthe\s+insight\s+everyone'?s?\s+missing\b/gi, /\bwhat\s+nobody\s+tells\s+you\b/gi, ]; // ─── Cutoff disclaimers ──────────────────────────────────────────── // Includes the canonical LLM self-identification phrases — these are // near-dispositive on their own (real humans don't write "as an AI // language model" in first person). Patterns cover the major model // families' default disclaimer language. const CUTOFF_DISCLAIMERS = [ /\bas\s+of\s+my\s+last\s+update\b/gi, /\bas\s+of\s+my\s+(?:knowledge\s+)?(?:cut-?off|last\s+training)\b/gi, /\bi\s+don'?t\s+have\s+access\s+to\s+real-?time\s+(?:data|information)\b/gi, /\bbased\s+on\s+available\s+information\b/gi, /\bas\s+an?\s+(?:ai|artificial\s+intelligence|large\s+language|ai\s+language)\s+(?:language\s+)?model\b/gi, /\bi\s+(?:am|'m)\s+an?\s+(?:ai|artificial\s+intelligence|large\s+language)\s+(?:assistant|model)?\b/gi, /\bi\s+cannot\s+(?:provide|give|offer)\s+(?:legal|medical|financial|professional)\s+advice\b/gi, /\bmy\s+training\s+data\s+(?:only\s+)?(?:goes\s+up\s+to|extends\s+to|ends\s+(?:in|at))\b/gi, ]; // ─── AI-tool fingerprints ────────────────────────────────────────── // Three near-definitive AI-origin signals adapted from // Aboudjem/humanizer-skill P33-P35 (see docs/competitive/audits/ // 2026-05-17-aboudjem-humanizer-skill.md). Unlike the statistical // patterns above, single hit on any of these is strong evidence — // the AI tool literally left its fingerprint in the text. // Unfilled slot-fill placeholders. Catches the canonical "[Your Name]" // family plus dated stubs and HTML/MD comments with placeholder verbs. const AI_PLACEHOLDERS = [ // Directive stubs ("[Your Name]", "[INSERT SOURCE URL]", // "[Describe the specific section]") — verb-led, the user was // told to fill in. /\[(?:Your|Insert|Add|Enter|Describe|Specify|Choose|Pick)[^\]\n]{1,80}\]/gi, // Noun-only template variables common in AI-generated email or // letter boilerplate. Match the bare noun OR noun + qualifier. // Conservative list: only nouns that almost never appear as // bracketed real content (citation refs, code identifiers, etc. // are excluded because they typically contain dots, slashes, // hyphens, or version numbers). /\[(?:Recipient|Sender|Topic|Subject|Salutation|Closing|Position|Department|Project Name|Company Name|Date)(?:\s+[^\]\n]{0,60})?\]/gi, // All-caps directive forms ("[INSERT X]", "[FILL IN]") — the // uppercase tells you it's a slot, not real content. /\[(?:INSERT|FILL\s+IN|ADD|TODO|TBD|PLACEHOLDER)[^\]\n]{0,80}\]/g, // Date stubs. /\b(?:19|20)\d{2}-XX-XX\b/g, /\bXX\/XX\/(?:19|20)\d{2}\b/g, // HTML/Markdown comment placeholders with placeholder verbs. //gi, ]; // Chatbot citation/markup tokens that leak through copy-paste. // `citeturn0search0` / `citeturn0news5` from ChatGPT, contentReference // tokens, oai_citation, attached_file references, grok_card markers. // Each is a near-definitive signature of a specific tool. const AI_CITATION_MARKUP = [ /\bcite(?:turn|news|search|navigation)\d+(?:search|turn|news|navigation)\d+/gi, /contentReference\s*\[oaicite:[^\]]+\]\s*\{[^}]*\}/gi, /\boai_citation\b/gi, /\[attached_file:\d+\]/gi, /\bgrok_card\b/gi, ]; // UTM/tracking parameters auto-appended by AI tools to URLs they // generate. Survives copy-paste even when nothing else does. const AI_UTM_SOURCE = [ /[?&]utm_source=(?:chatgpt|openai|copilot|claude|grok|gemini|perplexity)(?:\.com|\.ai)?\b/gi, /[?&]referrer=(?:chatgpt|copilot|grok|claude|gemini|perplexity)\.(?:com|ai)\b/gi, ]; // ─── Template phrases ────────────────────────────────────────────── const TEMPLATE_PHRASES = [ // template-phrase: only vague-praise adjectives. "a first step towards the full API", // "a small step towards cutting our storage bill" stay clean. /\ban?\s+(?:meaningful|significant|major|crucial|important|big|huge|bold|giant|monumental|pivotal|critical|key|vital|massive|tremendous|substantial|decisive|landmark|historic|exciting|transformative)\s+step\s+(?:towards?|forward)\b/gi, /\bwhether\s+you'?re\s+\w+\s+or\s+\w+/gi, /\bi\s+recently\s+had\s+the\s+pleasure\s+of\b/gi, ]; // ─── False concession ────────────────────────────────────────────── // "While X is impressive, Y remains a challenge" and "Although X has made // strides, Y is still an open question" only read as the AI tell when both // halves are vague: an opener that concedes nothing specific, paired with a // close that names no actual gap. The subject (X) is widened past a single // word — "while the underlying model architecture is impressive" is as // hollow as "while it is impressive" — but stays inside one clause (no // comma or sentence punctuation) so the opener cannot reach across clauses. // The close is required in the same sentence: a bare opener followed by a // concrete, specific continuation ("...at this scale, our write pattern is // append-only, so we moved the hot table to a log-structured store // instead") is ordinary technical writing, not the empty frame. See #211. // "Despite X challenges" is dropped entirely: alone it is too common a // shape in ordinary prose to carry the tell. // The close must also follow a clause separator (comma, semicolon or // colon): without one, "While the model is impressive and remains a // challenge to maintain, we plan to replace it next month" matched both // phrases inside the opening clause and never looked at the concrete main // clause that followed. See #359. // Stop at the next clause separator too: a concrete continuation followed // by a later vague phrase is not the empty two-half frame. const FALSE_CONCESSION_SUBJECT = "[^,;:.!?\\n]{1,60}?"; // Known limit: a period inside an abbreviation ("U.S.", "e.g.") ends the // gap the same as a real sentence boundary would, so a close on the far // side of one is deliberately missed to keep that boundary guarantee; // only a comma, semicolon or colon counts as the clause separator #359 // requires. const FALSE_CONCESSION_GAP = "[^,;:.!?\\n]{0,80}?[,;:]\\s*[^,;:.!?\\n]{0,80}?"; const FALSE_CONCESSION_VAGUE_CLOSE = "(?:remains?\\s+a\\s+challenge" + "|(?:is|are)\\s+still\\s+an?\\s+open\\s+questions?" + "|there\\s+(?:is|are)\\s+still\\s+work\\s+to\\s+do" + "|remains?\\s+unanswered)\\b"; const FALSE_CONCESSION = [ new RegExp("\\bwhile\\s+" + FALSE_CONCESSION_SUBJECT + "\\s+is\\s+impressive\\b" + FALSE_CONCESSION_GAP + FALSE_CONCESSION_VAGUE_CLOSE, 'gi'), new RegExp("\\balthough\\s+" + FALSE_CONCESSION_SUBJECT + "\\s+has\\s+made\\s+strides\\b" + FALSE_CONCESSION_GAP + FALSE_CONCESSION_VAGUE_CLOSE, 'gi'), ]; // ─── Rhetorical question openers ─────────────────────────────────── const RHETORICAL_QUESTIONS = [ /\bbut\s+what\s+does\s+this\s+mean\s+for\b/gi, /\bso\s+why\s+should\s+you\s+care\b/gi, /\bwhat'?s\s+next\?\s*/gi, ]; // ─── Hedge-stacked predictions ───────────────────────────────────── // Stacks a modal with a hedge adverb: "could potentially create new // opportunities", "may eventually unlock value." Either word alone is // fine; the stack is the tell. const HEDGE_STACK = [ // At most one intervening word, and never a negator. The old {0,2} gap // matched ordinary English: "could not possibly" (plain emphatic // negation) and inverted questions like "could a savage possibly" both // fired. Measured on the human-control corpus, 3 of 4 hedge-stack flags // were this over-match. See issue #69. /\b(?:could|may|might)\s+(?:(?!not\b|never\b|hardly\b|scarcely\b|barely\b)\w+\s+)?(?:potentially|eventually|ultimately|possibly|conceivably)\b/gi, /\b(?:potentially|eventually|ultimately)\s+(?:could|may|might)\b/gi, ]; // ─── Generic future-narrative closers ────────────────────────────── // The "may become one of the most important narratives" template — vague // future significance with no falsifiable claim. Covers narratives / // stories / trends / themes / chapters / movements. const FUTURE_NARRATIVE = [ /\b(?:may|could|will|is\s+(?:poised|set)\s+to)\s+become\s+(?:one\s+of\s+)?(?:the\s+)?(?:most\s+)?\w+\s+(?:narratives?|stories|developments?|trends?|movements?|chapters?|themes?|forces?)\b/gi, /\bone\s+of\s+the\s+most\s+important\s+(?:narratives?|stories|trends?|themes?)\s+of\s+the\s+(?:next|coming)\s+\w+\b/gi, ]; // ─── "Real/actual" adjective inflation ───────────────────────────── // "Real on-chain tokenomics", "actual reward sustainability" — using // real/actual/genuine/true as an empty intensifier on an abstract noun // to imply the rest of the field is fake/superficial. const REAL_ACTUAL_INFLATION = [ /\b(?:real|actual|genuine|true)\s+(?:on-?chain\s+)?(?:tokenomics|economics|utility|adoption|sustainability|impact|revenue|fundamentals|demand|value|innovation|traction)\b/gi, ]; // ─── Formulaic openers ───────────────────────────────────────────── // The "In the rapidly evolving world of X, Y has emerged as..." family // — LLM-default essay openers. const FORMULAIC_OPENERS = [ /\bin\s+the\s+(?:rapidly\s+|ever-?\s*)?(?:evolving|changing|expanding|growing|shifting)\s+(?:world|landscape|realm|space|field|domain|era)\s+of\b/gi, /\bin\s+(?:an?|the)\s+(?:digital\s+)?age\s+(?:where|of)\b/gi, /\bas\s+(?:we|the\s+world|society|industries?)\s+(?:continue|move|navigate|enter)\s+(?:to\s+)?(?:evolve|forward|into|through)\b/gi, // "has emerged as a leader/force/category" — gated to the inflated // nouns that signal pseudo-significance, since bare "has emerged as // a" matches normal English ("Rust has emerged as a serious systems // language"). Same gating for "has become increasingly". /\bhas\s+emerged\s+as\s+(?:a|the|one\s+of)\s+(?:leading|key|major|critical|essential|fundamental|pivotal|prominent|dominant|important)\s+\w+/gi, /\bhas\s+become\s+increasingly\s+(?:important|critical|popular|relevant|prominent|essential)\b/gi, ]; // ─── Speculative scenario openers ────────────────────────────────── // "Imagine a world where...", "Picture a future in which...", "Envision // a world where..." — the LLM habit of opening an argument with a // hypothetical that lists desirable outcomes instead of making a claim. // Gated to the world/future/reality object plus where/in-which so it // stays off instructional "imagine you have an array" (a teaching device // pointing at a concrete example, not a speculative world) and bare // "imagine that" asides. "consider a scenario where…" is deliberately // excluded: that is analytical framing common in technical reasoning, // not the marketing-opener tell. An optional short comma interrupter // catches the equally common "Imagine, for a moment, a world where…" // cadence. Known accepted false positive: fiction openings and staged // thought experiments match too — the engine has no fiction context // mode, so that call is left to the skill's carve-out (highlight-only; // a lone hit cannot flip a document's classification). const SPECULATIVE_OPENERS = [ /\b(?:imagine|picture|envision)(?:\s*,[^,\n]{1,30},)?\s+a\s+(?:world|future|reality)\s+(?:where|in\s+which)\b/gi, ]; // ─── Launch-copy dramatic introductions ──────────────────────────── // "Meet Flowdesk, your new favorite treasury dashboard" / "Think // Notion meets Figma" — the LLM-default product-introduction move // in launch and announcement copy. Both surfaces are gated to the // sentence-initial imperative followed by ONE capitalized token of 2 // to 30 characters, which is a recall limit: a two-token product name // ("Meet North Star", "Think Google Docs meets Microsoft Word") is a // deliberate miss. The Meet surface additionally requires one of four // launch-copy heads — "your new favorite", "your new go-to", and // "the new home/way/standard", the last three only when followed by // "of" / "to" / "in|for" or by end-of-clause punctuation. Without // that tail the head noun swallows a compound noun and ordinary prose // fires: "Meet Rosa, the new home secretary" and "Meet Emma, the new // way station manager" both matched before the tail was required. // Bare "Meet Sarah, your new account manager" is how humans introduce // colleagues, pets, and babies, so that form stays with the skill's // judgment side. Two surfaces from // the same family are deliberately NOT detected. "Say hello to X", // because "Say hello to Grandma." is ordinary human prose. And bare // "Enter X.", because the sentence-initial capitalized-noun form is // how UI and doc instructions are written: "Enter Password.", "Enter // Amount.", "Enter Username — your work email." Dropping the dash // terminator does not reach the period-terminated class, and neither // does a field-name denylist, so that surface stays with the skill's // judgment side and the UI forms are pinned as must-not-fire // fixtures. The anchors are lookbehinds so adjacent intros each // count and the reported span starts at the tell itself. const LAUNCH_INTROS = [ /(?<=^|[.!?]\s|\n)Meet\s+[A-Z][\w'-]{1,29}\s*,\s*(?:your\s+new\s+(?:favorite|go-to)\b|the\s+new\s+(?:home\s+of\b|way\s+to\b|standard\s+(?:in|for)\b|(?:standard|way|home)(?=\s*(?:[.!?,;:\u2013\u2014]|$))))/g, /(?<=^|[.!?]\s|\n)[Tt]hink\s+[A-Z][\w'-]{1,29}\s+meets\s+[A-Z][\w'-]{1,29}\b/g, ]; // ─── Dramatized contrast against the crowd ───────────────────────── // "shipped it in 2022, while everyone else was still debating // timelines" — a claim propped on an implied lagging crowd. The gate // is a dismissive verb PLUS the "was still" dramatization marker, // because bare "while everyone else" is ordinary simultaneity ("she // read while everyone else watched the movie") and even the // dismissive verbs are ordinary English in literal use ("others // debated the amendment" in wire copy). That gate is on this FIRST // branch only. Its stems are restricted to the -ing form, so the // adjective ("was still deliberate about the tradeoff"), the passive // ("was still debated by pundits") and the bare present ("was still // debates timelines") all stay clean — allowing e/es/ed let all // three through. The other two branches carry no "was still" // requirement: they match their own stereotyped wording ("writing // think-pieces", "playing catch-up"), and the skill entry scopes the // claim the same way. Verb stems carry explicit inflection tails so // agent nouns ("the market speculators") and adverbs ("deliberately // ignored") never match. Measured residue, all accepted: branch one // fires on ANY literal progressive use of its verbs ("while the // market was still speculating about the price"), not only on "was // still debating"; branches two and three fire on literal contrasts // of their own ("while everyone else wrote think-pieces from // Washington", "while everyone else played catch-up in the spring"). // Recall is deliberately sacrificed: "was busy debating" without // "still" stays a miss, per precision-over-recall. const CROWD_CONTRAST = [ /\bwhile\s+(?:everyone\s+else|the\s+(?:industry|market|competition)|others)\s+(?:was|were|is|are)\s+still\s+(?:busy\s+)?(?:(?:debat|deliberat|hesitat|theoriz|philosophiz|pontificat|speculat|argu)ing|(?:dither|bicker)ing)\b/gi, /\bwhile\s+(?:everyone\s+else|the\s+(?:industry|market|competition)|others)\s+(?:was\s+|were\s+)?(?:busy\s+)?(?:writing|wrote)\s+think-?\s?pieces\b/gi, /\bwhile\s+(?:everyone\s+else|the\s+(?:industry|market|competition)|others)\s+(?:was\s+|were\s+|is\s+|are\s+)?(?:still\s+)?play(?:ed|ing|s)?\s+catch[-\s]?up\b/gi, ]; // ─── Fake-casual props (stage directions and wink asides) ────────── // The regexable props from the fake-casual register: theatrical // asterisk stage directions ("*checks notes*", "*chef's kiss*", // "*mic drop*") and wink asides. Both lists are closed and short, and // that is a recall limit: exactly six stage directions ("checks // notes", "chef's kiss", "mic drop", "takes a deep breath", "sips // coffee|tea", "nervous laughter") and exactly four parentheticals, // the full (yes|no) x (really|seriously) grid. Neighbours in the same // register are deliberate misses: "*checks calendar*" and "(yes, // honestly)" do not fire. The kiss pattern requires the apostrophe — // making it optional matched the ordinary sentence "At midnight, // *chefs kiss* their spouses goodbye". // The rest of the register (one-word verdict closers, label-prefix // openers, the self-QA volley) needs register judgment and stays // skill-only — "wild." is a word, not a regex target. "because of // course …" joins them: a tense gate does not separate the wink from // the ordinary human grumble, because "The build failed because of // course it did." is that grumble in the same present-tense-plus-did // form the wink uses. Under precision-over-recall the surface is // judgment-only, and the grumble is pinned as a fixture. The kiss // pattern accepts the curly apostrophe (U+2019) — the form smart // punctuation and LLMs actually emit. Known accepted false positive: // a human writer using a wink aside on purpose; the props are // weighted as a strong single hit, not a classification by // themselves. const FAKE_CASUAL_PROPS = [ /\*\s?(?:checks\s+notes|chef['\u2019]s\s+kiss|mic\s+drop|takes\s+a\s+deep\s+breath|sips\s+(?:coffee|tea)|nervous\s+laughter)\s?\*/gi, /\(\s?(?:yes|no)\s?,\s?(?:really|seriously)\s?\)/gi, ]; // ─── Performed-insight phrases ───────────────────────────────────── // Essayist tics that announce profundity instead of delivering it. // Curated noun/complement lists keep precision high: "the whole family" // and "sit with him" are ordinary English and must not fire. Adapted // from Simon Willison's LLM cliché highlighter // (tools.simonwillison.net/llm-cliche-highlighter). const PERFORMED_INSIGHT = [ /\bsit(?:s|ting)?\s+with\s+(?:that|this)(?=\s*(?:[.!?,;:)\u2013\u2014\u2019"']|for\s+a\s+(?:moment|minute|second|beat)\b|$))(?:\s+for\s+a\s+(?:moment|minute|second|beat))?/gi, /\bsit(?:s|ting)?\s+with\s+(?:the|your)\s+(?:discomfort|tension|uncertainty|ambiguity|grief|unease)\b/gi, /\b(?:that|this|it|which)(?:['\u2019]s|\s+(?:is|was))\s+not\s+nothing\b/gi, /\byou\s+already\s+know\s+the\s+answer\b/gi, /\b(?:do\s+not|don['\u2019]t)\s+(?:have\s+to\s+)?take\s+my\s+word\s+for\s+it\b/gi, /(?<=^|[.!?]\s|\n)Turns\s+out\b/g, /(?:['\u2019]s|\b(?:is|was|are|were))\s+the\s+(?:whole|entire)\s+(?:point|game|ballgame|trick|pitch|idea|play|business\s+model|value\s+proposition)\b/gi, /\b(?:that|this)(?:['\u2019]s|\s+(?:is|was))\s+the\s+part\s+(?:that|I|you|we|nobody|no\s+one|most\s+people)\b/gi, /\bthe\s+only\s+[\w'\u2019-]+\s+that\s+(?:matters|counts)\b/gi, // "X is dead; long live Y" also names an essay or a literal succession // announcement. Whether the contrast earns its place needs reading (#351). /\b(?:that|this)(?:['\u2019]s|\s+(?:is|was))\s+why\s+[^.!?\n]{0,60}\s+mattered\b/gi, ]; const STAGED_DISCOVERY = [ // Staged discovery: a judgment framed as a twist the writer found ("the recording // turned out to be the least interesting part"). Superlative + insight noun keeps // ordinary "turned out to be the most expensive option" clean. /\b(?:turned|turns|turning)\s+out\s+to\s+be\s+the\s+(?:least|most)\s+(?:interesting|important|surprising|revealing|valuable|useful)\s+(?:part|thing|piece|bit)\b/gi, // Require a reveal-style continuation; "the real story was covered by..." // describes a literal story and is not a staged discovery. /\bthe\s+real\s+story\s+(?:here\s+)?(?:is|was)\b(?=\s+(?:the|that|how|why|what)\b)/gi, ]; // ─── Negation chains ─────────────────────────────────────────────── // "No fluff, no filler, no jargon" / "It didn't ask, didn't wait" / // "Don't call it X. Call it Y." Precision guards, in order: the // "no …" chain must open its sentence (mid-sentence inventories like // "takes no arguments, no headers, and no body" are factual, not // rhetorical); the "did not" chain must be comma-joined with the // subject elided ("I did not sleep. I did not eat" is ordinary // narration and stays clean); the stop-list keeps idiomatic pairs // ("no more, no less", "no matter what") from firing. Adapted from // Simon Willison's LLM cliché highlighter. const NO_ITEM_STOP = "(?!matter\\b|one\\b|doubt\\b|longer\\b|way\\b|less\\b|more\\b|such\\b|other\\b|means\\b)"; const NO_ITEM_SECOND_STOP = "(?!(?:in|on|at|of|to|for|with|from|by|is|are|was|were|be|been|being|will|would|can|could|should|shall|may|might|must|have|has|had|do|does|did)\\b)"; const NEGATION_CHAIN = [ new RegExp( "(?<=^|[.!?]\\s|\\n|[:\\u2013\\u2014]\\s)No\\s+" + NO_ITEM_STOP + "[a-z'\u2019-]+(?:\\s+" + NO_ITEM_SECOND_STOP + "[a-z'\u2019-]+)?" + "(?:\\s*,\\s*(?:and\\s+|or\\s+|just\\s+)?no\\s+" + NO_ITEM_STOP + "[a-z'\u2019-]+(?:\\s+" + NO_ITEM_SECOND_STOP + "[a-z'\u2019-]+)?){2,}", 'gm' ), /\b(?:did\s+not|didn['\u2019]t)\s+[a-z]+[^,.;!?\n]{0,20},\s*(?:did\s+not|didn['\u2019]t)\s+[a-z]+/gi, /\b(?:do\s+not|don['\u2019]t)\s+(?:just\s+)?(\w+)\s+it\b[^.!?\n]{0,60}[.!?;:,][\s'"\u201d\u2019]*(?:just\s+)?\1\s+it\b/gi, ]; // ─── Negative parallelism ────────────────────────────────────────── // "It's not just a search index, it's a foundation for trust." A frame is // a negated copula, a body X, then a restatement: "it / this / that / // they" + be. The engine splits frames in two (#351): // // reveal a minimizer (just / merely / simply), then a comma, // semicolon, colon, or dash and the restatement ("isn't just // raining, it's pouring"). The minimizer-then-upgrade move is // the tell itself, so a reveal flags on its own. // contrast the same joined frame without the minimizer ("isn't X, it's // Y", "isn't about X, it's about Y", "are not only X, they're // Y") and the split-sentence reveal ("isn't just X. It's Y."). // A single plain correction ("It isn't raining, it's // snowing.") is ordinary English, and references/patterns.md // allows one frame per piece, so a contrast flags only when // another frame of either kind starts within // NP_WINDOW_SENTENCES sentences of it. The stacked cadence is // the tell; two unrelated corrections paragraphs apart are // ordinary prose. "only" is not a reveal minimizer: the human // control corpus holds "fossil fuels are not only bad for our // environment, they're a losing bet". // // The restated pronoun is the gate. "not only X but (also) Y" and "not X // but Y" are ordinary correlatives and are not matched: on the human // control corpus "not only ... but" appeared 16 times in 143k human words // against 5 in 115k machine words. X is capped at 80 characters with no // comma or sentence punctuation, so a frame cannot reach across clauses. const NP_NEG = "(?:\\b(?:is|are|was|were)(?:n['\\u2019]t|\\s+not)|\\b(?:it|this|that|they|he|she|we|you)['\\u2019](?:s|re)\\s+not)"; const NP_MINIMIZER = "(?:just|merely|simply)"; const NP_BODY = "[^,;:.!?\\n\\u2014\\u2013]{1,80}?"; const NP_JOIN = "(?:\\s*[,;:]|\\s*[\\u2014\\u2013]|\\s+--)\\s*"; const NP_RESTATE = "(?:it|this|that|they)(?:['\\u2019](?:s|re)|\\s+(?:is|are|was|were))\\b"; const NEGATIVE_PARALLELISM_REVEAL = [ new RegExp(NP_NEG + "\\s+" + NP_MINIMIZER + "\\s+" + NP_BODY + NP_JOIN + NP_RESTATE, 'gi'), ]; const NEGATIVE_PARALLELISM_CONTRAST = [ new RegExp(NP_NEG + "\\s+(?!" + NP_MINIMIZER + "\\b)" + NP_BODY + NP_JOIN + NP_RESTATE, 'gi'), // Split-sentence reveal: the restatement opens the next sentence. new RegExp(NP_NEG + "\\s+" + NP_MINIMIZER + "\\s+" + NP_BODY + "[.!]\\s+" + NP_RESTATE, 'gi'), ]; // Two frames pair when their starting sentences are at most this many // sentences apart: the same sentence, the next, or the one after. const NP_WINDOW_SENTENCES = 2; // A blank line in LF, CRLF, or CR-only text. const NP_PARAGRAPH_BREAK = /(?:\r\n|\r(?!\n)|\n)[ \t]*(?:\r\n|\r|\n)/; // Reveals always flag. A contrast flags only when some other frame, reveal // or contrast, starts nearby. Sentence indexes come from the same coarse // splitter the highlight regions use. function negativeParallelismIssues(text, reveals, contrasts) { // Apply the proximity gate to the same distinct frames the caller reports. const distinctReveals = deduplicateIssues(reveals); const distinctContrasts = deduplicateIssues(contrasts); if (distinctContrasts.length === 0 || distinctReveals.length + distinctContrasts.length < 2) return distinctReveals; const frames = [...distinctReveals, ...distinctContrasts]; const starts = splitSentenceSpans(text).map(([start]) => start); const sentenceOf = (index) => { let lo = 0; let hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= index) lo = mid; else hi = mid - 1; } return lo; }; const sentences = frames.map((frame) => sentenceOf(frame.index)); // Paired frames must also share a paragraph: no blank line between them. const sameParagraph = (a, b) => !NP_PARAGRAPH_BREAK.test(text.slice(Math.min(a, b), Math.max(a, b))); const paired = distinctContrasts.filter((contrast, c) => { const i = distinctReveals.length + c; return sentences.some((other, j) => j !== i && frames[j].index !== contrast.index && Math.abs(other - sentences[i]) <= NP_WINDOW_SENTENCES && sameParagraph(frames[j].index, contrast.index)); }); return [...distinctReveals, ...paired].sort((a, b) => a.index - b.index); } // ─── Dev-blog boilerplate ────────────────────────────────────────── // Stock simplicity slogans from developer marketing. Adapted from // Simon Willison's LLM cliché highlighter. const DEV_BLOG_BOILERPLATE = [ /\bit\s+just\s+works\b(?!\s+out\b(?![-\s]+of[-\s]+the[-\s]+box\b))/gi, /\bzero[-\s]config(?:uration)?\b/gi, /\bsane\s+defaults\b/gi, /\b(?:hold|fit|fits|holds)\s+in\s+your\s+head\b/gi, ]; // Function words whose presence MID-title marks the AI section-header shape. // Word-anchored: without \b the "A" alternative matches inside any word and // the guard silently degrades to "four tokens". const FUNCTION_WORD = /\b(?:And|Or|Of|The|In|For|To|A|An)\b/; // Must accept exactly what TITLE_CASE_HEADER accepts, or the prefix survives // into the token count and reintroduces the ##-as-token bug. const MD_HEADING_PREFIX = /^#{1,6}[ \t]+/; /** Byte ranges covered by fenced code blocks, computed once per scan. * * A document that documents Markdown is the normal case for this rule -- a * fenced `## Heading` example is illustration, not the author's own section * header, and flagging it makes every docs page flag itself. * * This tracks the opening delimiter instead of counting them, because a * parity count is wrong on the very case the rule exists for. CommonMark * closes a fence only on the same character at the same length or longer, so * a four-backtick fence wrapping a three-backtick example -- exactly how you * document fences -- nests in practice, and counting delimiters inverts on * it. Up to three spaces of indent are legal. An unclosed fence runs to end * of document, matching how renderers treat it. * * Computed once per scan rather than rescanned per hit: the previous version * sliced the whole document for every candidate, which is quadratic on a * heading-dense file. */ function fenceRanges(text) { const re = /^[ \t]{0,3}(`{3,}|~{3,})([^\n]*)$/gm; const ranges = []; let open = null; let m; while ((m = re.exec(text)) !== null) { const marker = m[1]; if (!open) { open = { char: marker[0], len: marker.length, start: m.index }; } else if ( marker[0] === open.char && marker.length >= open.len && /^[ \t]*\r?$/.test(m[2]) ) { ranges.push([open.start, m.index + m[0].length]); open = null; } } if (open) ranges.push([open.start, text.length]); return ranges; } function inFenceRange(ranges, index) { return typeof index === 'number' && ranges.some(([a, b]) => index >= a && index < b); } function blankRange(chars, start, end) { for (let i = start; i < end && i < chars.length; i += 1) { if (chars[i] !== '\n') chars[i] = ' '; } } function inlineCodeRanges(text) { const runs = []; for (let i = 0; i < text.length;) { if (text[i] === '\n') { runs.push(null); i += 1; continue; } if (text[i] !== '`') { i += 1; continue; } const start = i; while (i < text.length && text[i] === '`') i += 1; runs.push({ start, end: i, length: i - start }); } const ranges = []; let lineStart = 0; while (lineStart < runs.length) { let lineEnd = runs.indexOf(null, lineStart); if (lineEnd === -1) lineEnd = runs.length; const nextByLength = new Map(); const nextSame = new Array(lineEnd - lineStart); for (let i = lineEnd - 1; i >= lineStart; i -= 1) { nextSame[i - lineStart] = nextByLength.get(runs[i].length); nextByLength.set(runs[i].length, i); } for (let i = lineStart; i < lineEnd;) { const close = nextSame[i - lineStart]; if (close === undefined) { i += 1; continue; } ranges.push([runs[i].start, runs[close].end]); i = close + 1; } lineStart = lineEnd + 1; } return ranges; } // Copy of the text with fenced blocks and inline code spans blanked out. // Index-preserving: each masked character becomes a space and newlines are // kept, so offsets into the result still address the same position in the // original. For rules where a character inside code is something the author // is quoting rather than using — a `#fff` in a CSS sample is not a tag. // Fences are blanked first so their backticks cannot pair with a later // inline span and swallow the prose between them. function maskCode(text) { const chars = text.split(''); for (const [a, b] of fenceRanges(text)) blankRange(chars, a, b); // Indented code blocks are deliberately NOT masked. Four spaces is a code // block only at top level; under a list marker it is a paragraph // continuation, so blanking it silences real tag blocks. #90 reports // fences and inline spans, and those are what this masks. const withoutFences = chars.join(''); for (const [start, end] of inlineCodeRanges(withoutFences)) blankRange(chars, start, end); return chars.join(''); } function initialFrontmatterRange(text) { const lines = []; const lineRe = /[^\r\n]*(?:\r\n|\n|\r|$)/g; let match; while ((match = lineRe.exec(text)) !== null && match[0]) { const body = match[0].replace(/(?:\r\n|\n|\r)$/, ''); lines.push({ body, start: match.index, end: match.index + body.length }); } if (lines.length < 3 || !/^---[ \t]*$/.test(lines[0].body.replace(/^\uFEFF/, ''))) return null; let closingLine = -1; for (let i = 1; i < lines.length; i += 1) { if (/^---[ \t]*$/.test(lines[i].body)) { closingLine = i; break; } } if (closingLine === -1) return null; // A pair of thematic breaks can also surround ordinary Markdown prose. // Require the first substantive line to begin like a YAML mapping entry // before treating the delimited block as frontmatter. Leading blank lines // and YAML comments are valid, and the line parser accepts LF, CRLF, or CR. const yamlKey = /^[ \t]*(?:[A-Za-z0-9_.-]+|"[^"\r\n]+"|'[^'\r\n]+')[ \t]*:/; const firstContent = lines .slice(1, closingLine) .find((line) => line.body.trim() && !/^[ \t]*#/.test(line.body)); if (!firstContent || !yamlKey.test(firstContent.body)) return null; return { start: 0, end: lines[closingLine].end }; } // Mask HTML comments in source order while tracking the Markdown constructs // that protect a literal ` … // A marker counts only as a whole line: the full comment, at most three // spaces of indent, nothing else on the line. Starts nest: each start needs // its own end, and the region runs from the outermost start to its matching // end. An unclosed start runs to the end of the text; an end with no open // start is ignored. The region is blanked in place, so offsets still // address the source. // // Markers are found by ONE left-to-right scan rather than a stack of masks, // because separate masks disagree about who owns overlapping text: a fence // inside a comment would swallow the comment's `-->`, and a `
` inside // a comment would open a container. After skipping initial YAML // frontmatter, the scan recognizes, in order of appearance, an HTML // comment, a Markdown fence, a top-level indented code line, an inline code // span, and an HTML,,