cleanpastedtext 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -131,3 +131,4 @@ export declare function cleanText(text: string, options: CleaningOptions): Clean
131
131
  * non-empty result always means real hidden characters are present.
132
132
  */
133
133
  export declare function detectHiddenCharacters(text: string): Detection[];
134
+ export * from "./signals.js";
package/dist/index.js CHANGED
@@ -1330,3 +1330,4 @@ export function cleanText(text, options) {
1330
1330
  export function detectHiddenCharacters(text) {
1331
1331
  return cleanText(text, PRESETS[DEFAULT_PRESET]).detections.filter((d) => d.action !== "kept" && d.category !== "typography" && d.category !== "normalization");
1332
1332
  }
1333
+ export * from "./signals.js";
@@ -0,0 +1,73 @@
1
+ /**
2
+ * AI-writing signals: a deterministic, explainable strength meter.
3
+ *
4
+ * Implements docs/research/ai-writing-signals-rulebook.md. It never claims
5
+ * authorship. It reports two different things:
6
+ *
7
+ * - residue: leftovers that chat interfaces put into copied text (citation
8
+ * tokens, document wrappers, assistant openers). Near-certain evidence that
9
+ * text was pasted from a chatbot, not that a model wrote the prose.
10
+ * - style: weak, probabilistic evidence from published research (excess
11
+ * vocabulary, phrase templates, formatting, em dashes, participial clauses),
12
+ * combined as capped log-likelihood points per family. "High" needs
13
+ * agreement from three independent families on at least 300 words.
14
+ *
15
+ * Every weight and threshold is a published-evidence prior, not yet
16
+ * calibrated on our own human holdout. LEXICON_VERSION dates the word lists,
17
+ * which go stale as models and writers change.
18
+ */
19
+ export declare const LEXICON_VERSION = "2026-11";
20
+ export type SignalGenre = "general" | "academic" | "email" | "news" | "casual" | "fiction";
21
+ export declare const SIGNAL_GENRES: Record<SignalGenre, string>;
22
+ export type SignalFamily = "vocabulary" | "phrases" | "formatting" | "typography" | "stylometry";
23
+ export declare const FAMILY_LABELS: Record<SignalFamily, string>;
24
+ export type SignalSource = {
25
+ title: string;
26
+ url: string;
27
+ };
28
+ export type StyleSignal = {
29
+ id: string;
30
+ family: SignalFamily;
31
+ label: string;
32
+ /** Up to 6 matched snippets, as they appear in the text. */
33
+ matches: string[];
34
+ /** Total matches before the snippet list was cut. */
35
+ count: number;
36
+ points: number;
37
+ note: string;
38
+ falsePositives: string;
39
+ source: SignalSource;
40
+ };
41
+ export type ResidueFinding = {
42
+ id: string;
43
+ label: string;
44
+ matches: string[];
45
+ count: number;
46
+ /** "definitive" for interface bugs; "strong" where humans sometimes write the same thing. */
47
+ strength: "definitive" | "strong";
48
+ note: string;
49
+ source: SignalSource;
50
+ };
51
+ export type SignalLevel = "not-enough-text" | "low" | "medium" | "high";
52
+ export type SignalReport = {
53
+ level: SignalLevel;
54
+ /** Sum of family points after caps. */
55
+ points: number;
56
+ words: number;
57
+ genre: SignalGenre;
58
+ families: {
59
+ family: SignalFamily;
60
+ points: number;
61
+ cap: number;
62
+ }[];
63
+ signals: StyleSignal[];
64
+ residue: ResidueFinding[];
65
+ /** Plain-language reasons for the level, e.g. why it was capped. */
66
+ notes: string[];
67
+ lexiconVersion: string;
68
+ };
69
+ /**
70
+ * Scores AI-writing signals in the raw text (run it before cleaning, so
71
+ * chat-interface residue is still there). Deterministic and local.
72
+ */
73
+ export declare function analyzeAiSignals(input: string, genre?: SignalGenre): SignalReport;
@@ -0,0 +1,603 @@
1
+ /**
2
+ * AI-writing signals: a deterministic, explainable strength meter.
3
+ *
4
+ * Implements docs/research/ai-writing-signals-rulebook.md. It never claims
5
+ * authorship. It reports two different things:
6
+ *
7
+ * - residue: leftovers that chat interfaces put into copied text (citation
8
+ * tokens, document wrappers, assistant openers). Near-certain evidence that
9
+ * text was pasted from a chatbot, not that a model wrote the prose.
10
+ * - style: weak, probabilistic evidence from published research (excess
11
+ * vocabulary, phrase templates, formatting, em dashes, participial clauses),
12
+ * combined as capped log-likelihood points per family. "High" needs
13
+ * agreement from three independent families on at least 300 words.
14
+ *
15
+ * Every weight and threshold is a published-evidence prior, not yet
16
+ * calibrated on our own human holdout. LEXICON_VERSION dates the word lists,
17
+ * which go stale as models and writers change.
18
+ */
19
+ export const LEXICON_VERSION = "2026-11";
20
+ export const SIGNAL_GENRES = {
21
+ general: "General",
22
+ academic: "Academic or technical",
23
+ email: "Business email",
24
+ news: "News or marketing",
25
+ casual: "Casual or social",
26
+ fiction: "Fiction",
27
+ };
28
+ export const FAMILY_LABELS = {
29
+ vocabulary: "Overused vocabulary",
30
+ phrases: "Phrase templates",
31
+ formatting: "Chat formatting",
32
+ typography: "Punctuation",
33
+ stylometry: "Sentence structure",
34
+ };
35
+ const FAMILY_CAPS = {
36
+ vocabulary: 4,
37
+ phrases: 4,
38
+ formatting: 2.5,
39
+ typography: 1,
40
+ stylometry: 2,
41
+ };
42
+ /* ------------------------------------------------------------------ */
43
+ /* Sources */
44
+ /* ------------------------------------------------------------------ */
45
+ const SRC = {
46
+ wpSigns: { title: "Wikipedia: Signs of AI writing", url: "https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing" },
47
+ wpMarkup: { title: "Wikipedia: Signs of AI writing, markup", url: "https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing/Markup" },
48
+ kobak: { title: "Kobak et al., excess vocabulary in PubMed (Science Advances 2025)", url: "https://arxiv.org/abs/2406.07016" },
49
+ liang: { title: "Liang et al., AI-modified peer reviews (ICML 2024)", url: "https://arxiv.org/abs/2403.07183" },
50
+ reinhart: { title: "Reinhart et al., grammatical style of LLMs (PNAS 2025)", url: "https://arxiv.org/abs/2410.16107" },
51
+ freeburg: { title: "Freeburg, em dash rates by model (arXiv 2603.27006, preprint)", url: "https://arxiv.org/abs/2603.27006" },
52
+ gengTrotta: { title: "Geng & Trotta, word use in arXiv after ChatGPT", url: "https://arxiv.org/abs/2404.08627" },
53
+ antislop: { title: "Antislop, over-represented fiction patterns (arXiv 2510.15061)", url: "https://arxiv.org/abs/2510.15061" },
54
+ pangram: { title: "Pangram, signs of AI writing (vendor corpus)", url: "https://www.pangram.com/signs-of-ai-writing" },
55
+ };
56
+ /* ------------------------------------------------------------------ */
57
+ /* Text helpers */
58
+ /* ------------------------------------------------------------------ */
59
+ const MAX_CHARS = 60_000;
60
+ const WORD = /[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu;
61
+ function words(text) {
62
+ return text.match(WORD) ?? [];
63
+ }
64
+ function sentences(text) {
65
+ return text
66
+ .replace(/\s+/g, " ")
67
+ .split(/(?<=[.!?…])\s+(?=["“'‘([]?[\p{Lu}\d])/u)
68
+ .map((s) => s.trim())
69
+ .filter((s) => words(s).length >= 3);
70
+ }
71
+ function snippet(text, index, length) {
72
+ const start = Math.max(0, index - 30);
73
+ const end = Math.min(text.length, index + length + 30);
74
+ return (start > 0 ? "…" : "") + text.slice(start, end).replace(/\s+/g, " ").trim() + (end < text.length ? "…" : "");
75
+ }
76
+ function findAll(text, pattern) {
77
+ const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g";
78
+ const re = new RegExp(pattern.source, flags);
79
+ const out = [];
80
+ let m;
81
+ while ((m = re.exec(text)) !== null) {
82
+ out.push({ match: m[0], index: m.index });
83
+ if (m[0].length === 0)
84
+ re.lastIndex++;
85
+ }
86
+ return out;
87
+ }
88
+ const round = (n) => Math.round(n * 100) / 100;
89
+ const RESIDUE_RULES = [
90
+ {
91
+ id: "chatgpt-citation",
92
+ label: "ChatGPT citation markers",
93
+ pattern: /contentReference\[oaicite:\d+\]|oai_citation|\bturn\d+(?:search|news|image|file|view|fetch)\d+|attributableIndex|[-]/,
94
+ strength: "definitive",
95
+ note: "Citation placeholders ChatGPT leaves in copied answers.",
96
+ source: SRC.wpMarkup,
97
+ },
98
+ {
99
+ id: "gemini-citation",
100
+ label: "Gemini citation markers",
101
+ pattern: /\[cite: ?\d+(?:, ?\d+)*\]|\[span_\d+\]\((?:start|end)_span\)/,
102
+ strength: "definitive",
103
+ note: "Source markers Gemini leaves in copied answers.",
104
+ source: SRC.wpMarkup,
105
+ },
106
+ {
107
+ id: "grok-citation",
108
+ label: "Grok markers",
109
+ pattern: /grok-card|grok_render_citation_card_json|referrer=grok\.com/,
110
+ strength: "definitive",
111
+ note: "Card and referral markers from Grok answers.",
112
+ source: SRC.wpMarkup,
113
+ },
114
+ {
115
+ id: "source-brackets",
116
+ label: "Chatbot source brackets (【…†…】)",
117
+ pattern: /【\d+(?::\d+)?†[^】\n]{0,40}】/,
118
+ strength: "definitive",
119
+ note: "Browsing citation format used by DeepSeek and older ChatGPT versions.",
120
+ source: SRC.wpMarkup,
121
+ },
122
+ {
123
+ id: "perplexity-citation",
124
+ label: "Perplexity markers",
125
+ pattern: /\[(?:attached_file|web):\d+\]|ppl-ai-file-upload/,
126
+ strength: "definitive",
127
+ note: "File and web citation markers from Perplexity answers.",
128
+ source: SRC.wpMarkup,
129
+ },
130
+ {
131
+ id: "writing-block",
132
+ label: "Chat document wrapper",
133
+ pattern: /:::writing\{variant="/,
134
+ strength: "definitive",
135
+ note: "A document block wrapper seen in chatbot output since mid-2026.",
136
+ source: SRC.wpMarkup,
137
+ },
138
+ {
139
+ id: "ai-utm",
140
+ label: "Links found through an AI assistant",
141
+ pattern: /utm_source=(?:chatgpt\.com|openai|copilot\.com)/,
142
+ strength: "strong",
143
+ note: "Shows an AI tool supplied the links, not that it wrote the text.",
144
+ source: SRC.wpSigns,
145
+ },
146
+ {
147
+ id: "placeholder",
148
+ label: "Unfilled template placeholders",
149
+ pattern: /\[(?:Your|Insert|Add|Describe)[^\]\n]{0,60}\]|\bINSERT_[A-Z_]+\b|\b20\d\d-(?:XX|xx)-(?:XX|xx)\b/,
150
+ strength: "strong",
151
+ note: "Placeholders a chatbot asked the user to fill in.",
152
+ source: SRC.wpSigns,
153
+ },
154
+ {
155
+ id: "assistant-opener",
156
+ label: "Chatbot reply opener",
157
+ pattern: /^(?:Certainly!|Of course!|Absolutely!|Sure!|Great question|Here(?:'s| is) (?:a|an|the|your)\b)/i,
158
+ strength: "strong",
159
+ anchor: "start",
160
+ note: "Opening lines of a chatbot reply left at the top of a document.",
161
+ source: SRC.wpSigns,
162
+ },
163
+ {
164
+ id: "assistant-closer",
165
+ label: "Chatbot reply sign-off",
166
+ pattern: /\b(?:I hope this helps|Let me know if you(?:'d| would)? (?:like|need|want)|Would you like me to|Is there anything else|Feel free to ask)\b/i,
167
+ strength: "strong",
168
+ anchor: "end",
169
+ skipGenres: ["email"],
170
+ note: "Closing offers of further help, typical of chatbot replies.",
171
+ source: SRC.wpSigns,
172
+ },
173
+ {
174
+ id: "assistant-identity",
175
+ label: "Model self-reference",
176
+ pattern: /\bas an AI(?: language model)?\b|\bas of my last (?:knowledge )?(?:update|training)\b|\bmy knowledge cutoff\b/i,
177
+ strength: "definitive",
178
+ note: "A model describing itself or its training cutoff.",
179
+ source: SRC.wpSigns,
180
+ },
181
+ {
182
+ id: "markdown-fence",
183
+ label: "Markdown code fence",
184
+ pattern: /^\x60{3}[\w-]*\s*$/m,
185
+ strength: "strong",
186
+ skipGenres: ["academic"],
187
+ note: "Code fences in prose usually come from a chat answer; normal in technical writing.",
188
+ source: SRC.wpMarkup,
189
+ },
190
+ ];
191
+ function detectResidue(text, genre) {
192
+ const sents = sentences(text);
193
+ const head = sents.slice(0, 2).join(" ");
194
+ const tail = sents.slice(-2).join(" ");
195
+ const found = [];
196
+ for (const rule of RESIDUE_RULES) {
197
+ if (rule.skipGenres?.includes(genre))
198
+ continue;
199
+ const scope = rule.anchor === "start" ? head : rule.anchor === "end" ? tail : text;
200
+ const hits = rule.anchor === "start"
201
+ ? (rule.pattern.test(scope.trimStart()) ? [{ match: scope.trimStart().slice(0, 60), index: 0 }] : [])
202
+ : findAll(scope, rule.pattern);
203
+ if (hits.length === 0)
204
+ continue;
205
+ found.push({
206
+ id: rule.id,
207
+ label: rule.label,
208
+ count: hits.length,
209
+ matches: hits.slice(0, 6).map((h) => (rule.anchor === "start" ? h.match : snippet(scope, h.index, h.match.length))),
210
+ strength: rule.strength,
211
+ note: rule.note,
212
+ source: rule.source,
213
+ });
214
+ }
215
+ return found;
216
+ }
217
+ /* ------------------------------------------------------------------ */
218
+ /* Family V: excess vocabulary */
219
+ /* ------------------------------------------------------------------ */
220
+ // Tier A: rare words with large measured excess; weight ≈ ln(excess ratio)
221
+ // from Kobak et al.'s released 2024 PubMed counts. Inflected forms differ.
222
+ const TIER_A = {
223
+ delves: 3.3, underscores: 2.6, delved: 2.5, showcasing: 2.4, meticulously: 2.3, delve: 2.1,
224
+ intricacies: 2.0, underscoring: 2.0, intricate: 2.0, surpassing: 2.0, delving: 1.9, commendable: 1.9,
225
+ underscore: 1.9, excels: 1.8, garnered: 1.7, underscored: 1.6, intricately: 1.6, realm: 1.6,
226
+ encompassed: 1.6, renowned: 1.6, grappling: 1.6, groundbreaking: 1.6, emphasizing: 1.5, encompassing: 1.5,
227
+ necessitating: 1.4, revolutionizing: 1.4, showcases: 1.3, showcased: 1.3, surpasses: 1.3, bolstering: 1.3,
228
+ comprehending: 1.3, endeavors: 1.3, advancements: 1.3, heightened: 1.3, notable: 1.2, unveiled: 1.2,
229
+ meticulous: 1.1, fostering: 1.1, leveraging: 1.1, seamlessly: 1.1, pivotal: 1.1, transformative: 1.1,
230
+ aligns: 1.1, multifaceted: 1.1,
231
+ };
232
+ // A′: review-register adjectives and adverbs from Liang et al. (no published weights).
233
+ const TIER_A_PRIME = {
234
+ noteworthy: 1, laudable: 1, invaluable: 1, versatile: 1, ingenious: 1, cogent: 1, lucidly: 1,
235
+ aptly: 1, innovatively: 1, methodically: 1, compellingly: 1, undeniably: 1,
236
+ };
237
+ // Tier B: common boosters, counted once per window.
238
+ const TIER_B = {
239
+ notably: 0.97, highlighting: 0.95, enhancing: 0.89, crucial: 0.75, insights: 0.71, valuable: 0.7,
240
+ additionally: 0.65, highlights: 0.65, exhibited: 0.64, comprehensive: 0.57, enhance: 0.57,
241
+ particularly: 0.55, diverse: 0.49,
242
+ };
243
+ /** Words whose use is ordinary in a genre's human writing. */
244
+ const GENRE_DAMPING = {
245
+ academic: { intricate: 0.5, crucial: 0.5, leveraging: 0.5, comprehensive: 0.5, notable: 0.5, insights: 0.5 },
246
+ news: { renowned: 0.5, unveiled: 0.5, groundbreaking: 0.5, notable: 0.5 },
247
+ };
248
+ const EARLY_ERA = new Set(["delve", "delves", "delved", "delving", "realm", "commendable", "meticulous", "meticulously", "intricate"]);
249
+ const WINDOW = 250;
250
+ function vocabularySignal(tokens, genre) {
251
+ if (genre === "fiction" || tokens.length === 0)
252
+ return null;
253
+ const damping = GENRE_DAMPING[genre] ?? {};
254
+ const lower = tokens.map((t) => t.toLowerCase());
255
+ const windows = Math.max(1, Math.round(lower.length / WINDOW));
256
+ const size = Math.ceil(lower.length / windows);
257
+ const hits = new Map();
258
+ let total = 0;
259
+ for (let w = 0; w < windows; w++) {
260
+ const slice = lower.slice(w * size, (w + 1) * size);
261
+ const counts = new Map();
262
+ for (const t of slice)
263
+ counts.set(t, (counts.get(t) ?? 0) + 1);
264
+ let windowScore = 0;
265
+ for (const [word, n] of counts) {
266
+ const a = TIER_A[word] ?? TIER_A_PRIME[word];
267
+ const b = TIER_B[word];
268
+ const d = damping[word] ?? 1;
269
+ if (a !== undefined)
270
+ windowScore += a * d * Math.min(n, 2);
271
+ else if (b !== undefined)
272
+ windowScore += b * d;
273
+ else
274
+ continue;
275
+ hits.set(word, (hits.get(word) ?? 0) + n);
276
+ }
277
+ total += windowScore;
278
+ }
279
+ // Mean across windows: a long text is not credited once per window.
280
+ const points = Math.min(FAMILY_CAPS.vocabulary, total / windows);
281
+ if (points < 0.5)
282
+ return null;
283
+ const listed = [...hits.entries()].sort((x, y) => y[1] - x[1]);
284
+ const early = listed.filter(([w]) => EARLY_ERA.has(w)).length;
285
+ return {
286
+ id: "excess-vocabulary",
287
+ family: "vocabulary",
288
+ label: "Words that spiked after ChatGPT",
289
+ matches: listed.slice(0, 6).map(([w, n]) => (n > 1 ? `${w} ×${n}` : w)),
290
+ count: listed.reduce((s, [, n]) => s + n, 0),
291
+ points: round(points),
292
+ note: "Weighted by how much more often each word appeared after ChatGPT (e.g. \"delves\" 28×, \"underscores\" 14× in 2024 PubMed abstracts)." +
293
+ (early > 0 ? " Some of these are 2023–24-era tells that newer models use less." : ""),
294
+ falsePositives: "Human writers have adopted many of these words, especially in tech, business and academic writing.",
295
+ source: SRC.kobak,
296
+ };
297
+ }
298
+ const PHRASE_RULES = [
299
+ {
300
+ id: "participial-tail",
301
+ label: "Sentences ending in an “-ing” comment",
302
+ pattern: /,\s+(?:further\s+)?(?:highlighting|underscoring|emphasizing|reflecting|symbolizing|showcasing|ensuring|contributing to|fostering|cultivating|encompassing|enhancing|solidifying|cementing)\b[^.!?]{3,}[.!?]/i,
303
+ perHit: 0.6,
304
+ cap: 2,
305
+ note: "e.g. “…, highlighting its importance.” GPT-4o uses present participial clauses at 5.3× the human rate.",
306
+ falsePositives: "Academic prose and press releases.",
307
+ source: SRC.reinhart,
308
+ },
309
+ {
310
+ id: "significance",
311
+ label: "Significance and legacy phrases",
312
+ pattern: /\b(?:stands?|serves?) as an? (?:testament|reminder)\b|\bplays? an? (?:crucial|pivotal|vital|key) role\b|\bmarks? an? (?:shift|turning point)\b|\bindelible mark\b|\bevolving landscape\b|\bdeeply rooted\b|\bsetting the stage for\b|\breflects? broader\b/i,
313
+ perHit: 0.5,
314
+ cap: 1.5,
315
+ distinct: true,
316
+ note: "Stock phrases that inflate importance.",
317
+ falsePositives: "Obituaries, tourism and PR copy.",
318
+ source: SRC.wpSigns,
319
+ },
320
+ {
321
+ id: "copula-avoidance",
322
+ label: "“Serves as” instead of “is”",
323
+ pattern: /\b(?:serves?|stands?|functions?|operates?) as (?:a|an|the)\b|\bboasts? (?:a|an)\b/i,
324
+ perHit: 0.3,
325
+ cap: 1,
326
+ note: "LLM revisions replace “is/are” with “serves as”, “stands as”, “boasts”.",
327
+ falsePositives: "Technical documentation (“serves as a proxy”).",
328
+ source: SRC.gengTrotta,
329
+ skipGenres: ["news"],
330
+ },
331
+ {
332
+ id: "negative-parallelism",
333
+ label: "“Not only… but”, “it's not X, it's Y”",
334
+ pattern: /\bnot only\b[^.]{1,80}\bbut(?: also)?\b|\b(?:it'?s|it is|this is|that'?s|that is) not (?:just |merely |only |about )?[^.;]{1,50}[,;—–-]\s*(?:it'?s|it is|this is|but)\b|\bno [^,.]{1,25}, no [^,.]{1,25}, just\b/i,
335
+ perHit: 0.4,
336
+ cap: 1.2,
337
+ note: "Contrastive framing; modest overuse in AI text, strongly genre-dependent.",
338
+ falsePositives: "Speeches, LinkedIn posts, myth-busting articles.",
339
+ source: SRC.pangram,
340
+ },
341
+ {
342
+ id: "corrective-framing",
343
+ label: "Corrective framing (2026)",
344
+ pattern: /\bdoes not (?:by itself )?establish\b|\bshould not be confused with\b|\bshould (?:not )?be (?:treated|presented|understood) as\b[^.]{0,80}\brather than\b/i,
345
+ perHit: 0.8,
346
+ cap: 1.6,
347
+ distinct: true,
348
+ note: "A pattern Wikipedia editors date to mid-2026 models.",
349
+ falsePositives: "Legal and philosophical writing.",
350
+ source: SRC.wpSigns,
351
+ },
352
+ {
353
+ id: "availability-hedge",
354
+ label: "Hedging about available sources",
355
+ pattern: /\b(?:specific )?details are (?:limited|scarce)\b|\bnot widely (?:documented|available|disclosed)\b|\bbased on (?:the )?available information\b|\bin the (?:provided|available) (?:sources|search results)\b/i,
356
+ perHit: 1,
357
+ cap: 2,
358
+ distinct: true,
359
+ note: "The most common live sign on Wikipedia as of October 2026.",
360
+ falsePositives: "Journalism (“details are scarce”).",
361
+ source: SRC.wpSigns,
362
+ },
363
+ {
364
+ id: "coverage-emphasis",
365
+ label: "Emphasis on media coverage and listings",
366
+ pattern: /\b(?:independent|national|regional|trade) (?:media )?(?:coverage|outlets|publications)\b|\bmaintains an? (?:active|strong) (?:digital|online|social media) presence\b/i,
367
+ perHit: 0.8,
368
+ cap: 1.6,
369
+ distinct: true,
370
+ note: "A pattern Wikipedia editors date to GPT-5-era output.",
371
+ falsePositives: "PR and biography drafts.",
372
+ source: SRC.wpSigns,
373
+ },
374
+ {
375
+ id: "vague-association",
376
+ label: "Vague “associated with” phrasing",
377
+ pattern: /\bin (?:connection|association) with\b|\b(?:was|is|has been) associated with\b/i,
378
+ perHit: 0.3,
379
+ cap: 0.9,
380
+ note: "Vague connection phrasing; common in 2026 AI text.",
381
+ falsePositives: "Medicine and science, where “associated with” is precise.",
382
+ source: SRC.wpSigns,
383
+ skipGenres: ["academic"],
384
+ },
385
+ {
386
+ id: "challenges-formula",
387
+ label: "“Despite its challenges…” formula",
388
+ pattern: /(?:^|\n)\s*Despite (?:its|these|their)\b[^.\n]{0,120}\bchallenges\b|(?:^|\n)#*\s*(?:Challenges and [A-Z]\w+|Future Outlook)\s*$/m,
389
+ perHit: 0.8,
390
+ cap: 0.8,
391
+ note: "A rigid challenges-then-optimism closing formula.",
392
+ falsePositives: "Reports and grant writing.",
393
+ source: SRC.wpSigns,
394
+ },
395
+ {
396
+ id: "scaffolds",
397
+ label: "Didactic and summary scaffolds",
398
+ pattern: /\bit'?s (?:important|worth|crucial) to (?:note|remember|consider)\b|(?:^|\n)\s*In (?:summary|conclusion),/i,
399
+ perHit: 0.3,
400
+ cap: 0.6,
401
+ distinct: true,
402
+ note: "Older tells; Wikipedia files them as historical.",
403
+ falsePositives: "Student essays taught to use these templates.",
404
+ source: SRC.wpSigns,
405
+ },
406
+ {
407
+ id: "fiction-slop",
408
+ label: "Over-used fiction phrasing",
409
+ pattern: /\b(?:flicker(?:ed|ing)|murmur(?:ed|ing)|voice barely above a whisper|air (?:was )?thick with|eyes never leaving|took a deep breath|a testament to)\b|\bgaze\b/i,
410
+ perHit: 0.5,
411
+ cap: 2.5,
412
+ distinct: true,
413
+ note: "Patterns shared across 67 models, some over 1,000× the human rate.",
414
+ falsePositives: "Genre fiction and fan fiction.",
415
+ source: SRC.antislop,
416
+ genres: ["fiction"],
417
+ },
418
+ ];
419
+ function phraseSignals(text, genre) {
420
+ const out = [];
421
+ for (const rule of PHRASE_RULES) {
422
+ if (rule.genres && !rule.genres.includes(genre))
423
+ continue;
424
+ if (rule.skipGenres?.includes(genre))
425
+ continue;
426
+ const hits = findAll(text, rule.pattern);
427
+ if (hits.length === 0)
428
+ continue;
429
+ const units = rule.distinct ? new Set(hits.map((h) => h.match.toLowerCase().trim())).size : hits.length;
430
+ const points = Math.min(rule.cap, units * rule.perHit);
431
+ out.push({
432
+ id: rule.id,
433
+ family: "phrases",
434
+ label: rule.label,
435
+ matches: hits.slice(0, 6).map((h) => snippet(text, h.index, h.match.length)),
436
+ count: hits.length,
437
+ points: round(points),
438
+ note: rule.note,
439
+ falsePositives: rule.falsePositives,
440
+ source: rule.source,
441
+ });
442
+ }
443
+ return out;
444
+ }
445
+ /* ------------------------------------------------------------------ */
446
+ /* Family F: chat formatting */
447
+ /* ------------------------------------------------------------------ */
448
+ function formattingSignals(text, genre) {
449
+ const scale = genre === "academic" ? 0.3 : 1;
450
+ const rules = [
451
+ {
452
+ id: "inline-header-list",
453
+ label: "List items that start with a bold label and a colon",
454
+ pattern: /^\s*(?:[-*•–]|\d+\.)\s*(?:\*\*)?[A-Z][^:\n*]{1,50}(?::\*\*|\*\*:|:)\s+\S/m,
455
+ min: 2,
456
+ points: 1,
457
+ note: "e.g. “• Speed: …”. The most specific chat list format; survives copying as plain text.",
458
+ },
459
+ { id: "bold-density", label: "Frequent **bold** phrases", pattern: /\*\*[^*\n]{2,60}\*\*/, min: 3, points: 0.5, note: "Markdown bold left in the text." },
460
+ { id: "markdown-headings", label: "Markdown headings", pattern: /^#{1,4}\s+\S/m, min: 2, points: 0.5, note: "“## Heading” lines from a chat answer." },
461
+ {
462
+ id: "emoji-bullets",
463
+ label: "Emoji at the start of headings or bullets",
464
+ pattern: /^\s*(?:[-*•]\s*|#{1,4}\s*)?\p{Extended_Pictographic}/mu,
465
+ min: 2,
466
+ points: 0.5,
467
+ note: "Decorative emoji before list items or headings.",
468
+ },
469
+ { id: "dividers", label: "Horizontal-rule dividers", pattern: /^\s*(?:---|\*\*\*)\s*$/m, min: 2, points: 0.3, note: "“---” between every section." },
470
+ ];
471
+ const out = [];
472
+ for (const rule of rules) {
473
+ const hits = findAll(text, rule.pattern);
474
+ if (hits.length < rule.min)
475
+ continue;
476
+ out.push({
477
+ id: rule.id,
478
+ family: "formatting",
479
+ label: rule.label,
480
+ matches: hits.slice(0, 4).map((h) => snippet(text, h.index, h.match.length)),
481
+ count: hits.length,
482
+ points: round(rule.points * scale),
483
+ note: rule.note,
484
+ falsePositives: "Developers, note-taking apps (Obsidian, Notion), Reddit and slide notes use Markdown natively.",
485
+ source: rule.id === "inline-header-list" ? SRC.wpSigns : SRC.pangram,
486
+ });
487
+ }
488
+ return out;
489
+ }
490
+ /* ------------------------------------------------------------------ */
491
+ /* Family T: em dashes */
492
+ /* ------------------------------------------------------------------ */
493
+ function emDashSignal(text, wordCount, genre) {
494
+ const dashes = findAll(text, /—/);
495
+ const perThousand = (dashes.length / Math.max(wordCount, 1)) * 1000;
496
+ const threshold = genre === "news" ? 9 : 6;
497
+ if (wordCount < 300 || dashes.length < 3 || perThousand < threshold)
498
+ return null;
499
+ return {
500
+ id: "em-dash-rate",
501
+ family: "typography",
502
+ label: `Em dashes: ${perThousand.toFixed(1)} per 1,000 words`,
503
+ matches: dashes.slice(0, 4).map((h) => snippet(text, h.index, 1)),
504
+ count: dashes.length,
505
+ points: 1,
506
+ note: "Some models use 7–11 per 1,000 words (GPT-4.1, Claude); published human essays average about 3. GPT-5.x, Gemini and Llama use few, so an absence proves nothing.",
507
+ falsePositives: "Literary and magazine writing; human baselines vary about 10× by corpus.",
508
+ source: SRC.freeburg,
509
+ };
510
+ }
511
+ /* ------------------------------------------------------------------ */
512
+ /* Family S: participial clauses */
513
+ /* ------------------------------------------------------------------ */
514
+ function participialSignal(sents) {
515
+ if (sents.length < 8)
516
+ return null;
517
+ const opener = /^(?:[A-Z][a-z]+ing)\b[^,]{0,60},/;
518
+ // Comma-led -ing tails not already covered by the participial-tail phrase rule.
519
+ const tail = /,\s+(?!(?:further\s+)?(?:highlighting|underscoring|emphasizing|reflecting|symbolizing|showcasing|ensuring|contributing|fostering|cultivating|encompassing|enhancing|solidifying|cementing)\b)[a-z]+ing\b[^.!?]{3,}[.!?]$/;
520
+ const matched = sents.filter((s) => opener.test(s) || tail.test(s));
521
+ const rate = matched.length / sents.length;
522
+ if (matched.length < 3 || rate < 0.2)
523
+ return null;
524
+ return {
525
+ id: "participial-clauses",
526
+ family: "stylometry",
527
+ label: `“-ing” clauses in ${Math.round(rate * 100)}% of sentences`,
528
+ matches: matched.slice(0, 4).map((s) => (s.length > 140 ? s.slice(0, 137) + "…" : s)),
529
+ count: matched.length,
530
+ points: rate >= 1 / 3 ? 1 : 0.5,
531
+ note: "Instruction-tuned models use present participial clauses at 2–5× the human rate. Threshold is provisional until measured on our own human texts.",
532
+ falsePositives: "Narrative fiction and descriptive writing.",
533
+ source: SRC.reinhart,
534
+ };
535
+ }
536
+ /* ------------------------------------------------------------------ */
537
+ /* Scoring */
538
+ /* ------------------------------------------------------------------ */
539
+ const MIN_STYLE_WORDS = 150;
540
+ const FULL_STYLE_WORDS = 300;
541
+ /**
542
+ * Scores AI-writing signals in the raw text (run it before cleaning, so
543
+ * chat-interface residue is still there). Deterministic and local.
544
+ */
545
+ export function analyzeAiSignals(input, genre = "general") {
546
+ const text = input.length > MAX_CHARS ? input.slice(0, MAX_CHARS) : input;
547
+ const tokens = words(text);
548
+ const wordCount = tokens.length;
549
+ const residue = detectResidue(text, genre);
550
+ const notes = [];
551
+ const base = {
552
+ level: "not-enough-text",
553
+ points: 0,
554
+ words: wordCount,
555
+ genre,
556
+ families: [],
557
+ signals: [],
558
+ residue,
559
+ notes,
560
+ lexiconVersion: LEXICON_VERSION,
561
+ };
562
+ if (input.length > MAX_CHARS)
563
+ notes.push(`Only the first ${MAX_CHARS.toLocaleString("en-US")} characters were analyzed.`);
564
+ if (wordCount < MIN_STYLE_WORDS) {
565
+ notes.push(`Style needs at least ${MIN_STYLE_WORDS} words to assess; this text has ${wordCount}.`);
566
+ return base;
567
+ }
568
+ const signals = [];
569
+ const vocab = vocabularySignal(tokens, genre);
570
+ if (vocab)
571
+ signals.push(vocab);
572
+ signals.push(...phraseSignals(text, genre));
573
+ signals.push(...formattingSignals(text, genre));
574
+ if (wordCount >= FULL_STYLE_WORDS) {
575
+ const dash = emDashSignal(text, wordCount, genre);
576
+ if (dash)
577
+ signals.push(dash);
578
+ const part = participialSignal(sentences(text));
579
+ if (part)
580
+ signals.push(part);
581
+ }
582
+ else {
583
+ notes.push(`Rate-based checks (em dashes, sentence structure) need ${FULL_STYLE_WORDS}+ words.`);
584
+ }
585
+ const families = Object.keys(FAMILY_CAPS)
586
+ .map((family) => {
587
+ const raw = signals.filter((s) => s.family === family).reduce((sum, s) => sum + s.points, 0);
588
+ return { family, points: round(Math.min(FAMILY_CAPS[family], raw)), cap: FAMILY_CAPS[family] };
589
+ })
590
+ .filter((f) => f.points > 0);
591
+ const points = round(families.reduce((sum, f) => sum + f.points, 0));
592
+ const familyCount = families.length;
593
+ let level = "low";
594
+ if (points >= 5 && familyCount >= 3 && wordCount >= FULL_STYLE_WORDS)
595
+ level = "high";
596
+ else if (points >= 2.5 && familyCount >= 2)
597
+ level = "medium";
598
+ if (level !== "high" && points >= 5 && familyCount >= 3)
599
+ notes.push(`Capped at Medium: High needs ${FULL_STYLE_WORDS}+ words.`);
600
+ if (level === "low" && points >= 2.5 && familyCount < 2)
601
+ notes.push("Capped at Low: the signals all come from one family.");
602
+ return { ...base, level, points, families, signals: signals.sort((a, b) => b.points - a.points) };
603
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cleanpastedtext",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Detect and remove hidden Unicode (zero-width spaces, BiDi controls, tag characters), odd spaces and AI-style typography from text. Deterministic, dependency-free, runs locally.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",