cleanpastedtext 0.1.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
@@ -22,6 +22,8 @@
22
22
  * an emoji and are always removed when the variation-selector pass is on.
23
23
  */
24
24
  export type DetectionCategory = "ai-artifact" | "invisible" | "bidi" | "tag" | "variation-selector" | "control" | "space" | "typography"
25
+ /** Citation and entity markers left behind when an AI chat answer is copied (e.g. ChatGPT's oaicite). */
26
+ | "chat-artifact"
25
27
  /** Changes made by the NFKC and whitespace stages rather than by a character strip. */
26
28
  | "normalization";
27
29
  export type DetectionAction = "removed" | "replaced" | "kept";
@@ -53,10 +55,21 @@ export type CleaningStats = {
53
55
  /** Hard-wrapped line breaks joined inside paragraphs, plus words rejoined across a line-end hyphen. */
54
56
  linesJoined: number;
55
57
  };
58
+ /** A message decoded from invisible characters found in the input. */
59
+ export type HiddenMessage = {
60
+ /** "tag": Unicode tag characters (U+E0020–U+E007E) spelling ASCII text. "variation-selector": bytes encoded as variation selectors after a visible character. */
61
+ kind: "tag" | "variation-selector";
62
+ /** The decoded text (truncated to 500 characters). */
63
+ text: string;
64
+ /** Number of invisible characters that carried it. */
65
+ carriers: number;
66
+ };
56
67
  export type CleaningResult = {
57
68
  cleanedText: string;
58
69
  stats: CleaningStats;
59
70
  detections: Detection[];
71
+ /** Readable messages decoded from invisible characters in the original text. Empty when none. */
72
+ hiddenMessages: HiddenMessage[];
60
73
  };
61
74
  export type CleaningOptions = {
62
75
  normalizeUnicode?: boolean;
@@ -88,6 +101,13 @@ export type CleaningOptions = {
88
101
  * starts with a lowercase letter.
89
102
  */
90
103
  joinLines?: boolean;
104
+ /**
105
+ * Remove citation and entity markers that AI chat apps leave in copied text,
106
+ * such as ChatGPT's ":contentReference[oaicite:0]{index=0}", "【4†source】" and
107
+ * the private-use "cite turn0search0" markers. Entity markers keep their
108
+ * display name.
109
+ */
110
+ removeChatArtifacts?: boolean;
91
111
  };
92
112
  export declare const DEFAULT_PRESET = "AI Clean";
93
113
  export declare const PRESETS: Record<string, CleaningOptions>;
@@ -95,6 +115,13 @@ export declare const PRESETS: Record<string, CleaningOptions>;
95
115
  export declare const PRESET_DESCRIPTIONS: Record<string, string>;
96
116
  export declare function formatCodepoint(cp: number): string;
97
117
  export declare function codepointName(cp: number): string;
118
+ /**
119
+ * Decodes the two known ways of hiding text in invisible characters:
120
+ * runs of Unicode tag characters that spell ASCII (outside real emoji flag
121
+ * sequences), and "emoji smuggling", where each byte of a UTF-8 message is a
122
+ * variation selector (U+FE00–U+FE0F for 0–15, U+E0100–U+E01EF for 16–255).
123
+ */
124
+ export declare function findHiddenMessages(text: string): HiddenMessage[];
98
125
  export declare function cleanText(text: string, options: CleaningOptions): CleaningResult;
99
126
  /**
100
127
  * Scans text for hidden characters and AI watermark artifacts without
@@ -104,3 +131,4 @@ export declare function cleanText(text: string, options: CleaningOptions): Clean
104
131
  * non-empty result always means real hidden characters are present.
105
132
  */
106
133
  export declare function detectHiddenCharacters(text: string): Detection[];
134
+ export * from "./signals.js";
package/dist/index.js CHANGED
@@ -24,6 +24,7 @@
24
24
  export const DEFAULT_PRESET = "AI Clean";
25
25
  export const PRESETS = {
26
26
  "AI Clean": {
27
+ removeChatArtifacts: true,
27
28
  normalizeUnicode: true,
28
29
  removeInvisibleChars: true,
29
30
  removeJoinControls: true,
@@ -38,6 +39,7 @@ export const PRESETS = {
38
39
  plainAscii: false,
39
40
  },
40
41
  "Safe Clean": {
42
+ removeChatArtifacts: true,
41
43
  normalizeUnicode: true,
42
44
  removeInvisibleChars: true,
43
45
  removeJoinControls: true,
@@ -52,6 +54,7 @@ export const PRESETS = {
52
54
  plainAscii: false,
53
55
  },
54
56
  "Keep Typography": {
57
+ removeChatArtifacts: true,
55
58
  normalizeUnicode: true,
56
59
  removeInvisibleChars: true,
57
60
  removeJoinControls: true,
@@ -66,6 +69,7 @@ export const PRESETS = {
66
69
  plainAscii: false,
67
70
  },
68
71
  "Plain ASCII": {
72
+ removeChatArtifacts: true,
69
73
  normalizeUnicode: true,
70
74
  removeInvisibleChars: true,
71
75
  removeJoinControls: true,
@@ -80,10 +84,12 @@ export const PRESETS = {
80
84
  plainAscii: true,
81
85
  },
82
86
  "Markdown to Text": {
87
+ removeChatArtifacts: true,
83
88
  stripMarkdown: true,
84
89
  normalizeWhitespace: true,
85
90
  },
86
91
  "Join Lines": {
92
+ removeChatArtifacts: true,
87
93
  normalizeUnicode: true,
88
94
  removeInvisibleChars: true,
89
95
  removeJoinControls: true,
@@ -163,6 +169,65 @@ function isSupplementaryVariationSelector(cp) {
163
169
  function isVariationSelector(cp) {
164
170
  return (cp >= 0xfe00 && cp <= 0xfe0f) || isSupplementaryVariationSelector(cp);
165
171
  }
172
+ const INVISIBLE_INFO = { category: "invisible", disposition: "remove" };
173
+ const FLAG_INFO = { category: "control", disposition: "flag" };
174
+ /**
175
+ * Format characters with a visible or script-specific job, left alone even
176
+ * though Unicode classes them as format (Cf) or default-ignorable: Arabic,
177
+ * Syriac and Kaithi number signs that print above digits, Egyptian
178
+ * hieroglyph and Duployan shorthand format controls.
179
+ */
180
+ function isScriptFormatChar(cp) {
181
+ return ((cp >= 0x0600 && cp <= 0x0605) ||
182
+ cp === 0x06dd ||
183
+ cp === 0x070f ||
184
+ cp === 0x0890 ||
185
+ cp === 0x0891 ||
186
+ cp === 0x08e2 ||
187
+ cp === 0x110bd ||
188
+ cp === 0x110cd ||
189
+ (cp >= 0x13430 && cp <= 0x1345f) ||
190
+ (cp >= 0x1bca0 && cp <= 0x1bca3));
191
+ }
192
+ /**
193
+ * Joiners that spell words in some scripts: ZWNJ/ZWJ (Persian, Indic) and the
194
+ * Mongolian free variation selectors. They share the removeJoinControls switch.
195
+ */
196
+ function isScriptJoinControl(cp) {
197
+ return cp === 0x200c || cp === 0x200d || (cp >= 0x180b && cp <= 0x180d) || cp === 0x180f;
198
+ }
199
+ const IGNORABLE = /[\p{Default_Ignorable_Code_Point}\p{Cf}]/u;
200
+ const PRIVATE_USE = /\p{Co}/u;
201
+ const NONCHARACTER = /\p{Noncharacter_Code_Point}/u;
202
+ const PROPERTY_CACHE = new Map();
203
+ /**
204
+ * Everything the hand-written tables above do not name, classified from the
205
+ * Unicode properties built into the JavaScript engine, so coverage follows
206
+ * the Unicode version of the browser or Node.js running it: every
207
+ * default-ignorable or format character becomes "invisible", private-use
208
+ * characters and noncharacters become "control", and U+FFFD is flagged.
209
+ */
210
+ function classifyByProperty(cp) {
211
+ if (cp < 0xad)
212
+ return null;
213
+ const cached = PROPERTY_CACHE.get(cp);
214
+ if (cached !== undefined)
215
+ return cached;
216
+ const ch = String.fromCodePoint(cp);
217
+ let info = null;
218
+ if (cp === 0x2800)
219
+ info = { category: "invisible", disposition: "space" };
220
+ else if (cp === 0xfffd)
221
+ info = FLAG_INFO;
222
+ else if (isScriptFormatChar(cp))
223
+ info = null;
224
+ else if (IGNORABLE.test(ch))
225
+ info = INVISIBLE_INFO;
226
+ else if (PRIVATE_USE.test(ch) || NONCHARACTER.test(ch))
227
+ info = CONTROL_INFO;
228
+ PROPERTY_CACHE.set(cp, info);
229
+ return info;
230
+ }
166
231
  function classify(cp) {
167
232
  const single = CHAR_INFO.get(cp);
168
233
  if (single)
@@ -176,7 +241,7 @@ function classify(cp) {
176
241
  (cp >= 0x80 && cp <= 0x9f)) {
177
242
  return CONTROL_INFO;
178
243
  }
179
- return null;
244
+ return classifyByProperty(cp);
180
245
  }
181
246
  // Typography characters — counted only when typography normalization is on.
182
247
  const TYPOGRAPHY_CPS = new Set([
@@ -207,7 +272,11 @@ const SINGLE_NAMES = {
207
272
  0x1160: "Hangul jungseong filler",
208
273
  0x17b4: "Khmer vowel inherent aq",
209
274
  0x17b5: "Khmer vowel inherent aa",
275
+ 0x180b: "Mongolian free variation selector one",
276
+ 0x180c: "Mongolian free variation selector two",
277
+ 0x180d: "Mongolian free variation selector three",
210
278
  0x180e: "Mongolian vowel separator",
279
+ 0x180f: "Mongolian free variation selector four",
211
280
  0x2000: "En quad",
212
281
  0x2001: "Em quad",
213
282
  0x2002: "En space",
@@ -241,6 +310,17 @@ const SINGLE_NAMES = {
241
310
  0x202f: "Narrow no-break space",
242
311
  0x205f: "Medium mathematical space",
243
312
  0x2060: "Word joiner",
313
+ 0x2061: "Function application (invisible)",
314
+ 0x2062: "Invisible times",
315
+ 0x2063: "Invisible separator",
316
+ 0x2064: "Invisible plus",
317
+ 0x206a: "Inhibit symmetric swapping (deprecated)",
318
+ 0x206b: "Activate symmetric swapping (deprecated)",
319
+ 0x206c: "Inhibit Arabic form shaping (deprecated)",
320
+ 0x206d: "Activate Arabic form shaping (deprecated)",
321
+ 0x206e: "National digit shapes (deprecated)",
322
+ 0x206f: "Nominal digit shapes (deprecated)",
323
+ 0x2800: "Braille pattern blank",
244
324
  0x2066: "Left-to-right isolate",
245
325
  0x2067: "Right-to-left isolate",
246
326
  0x2068: "First strong isolate",
@@ -255,6 +335,15 @@ const SINGLE_NAMES = {
255
335
  0xfffa: "Interlinear annotation separator",
256
336
  0xfffb: "Interlinear annotation terminator",
257
337
  0xfffc: "Object replacement character",
338
+ 0xfffd: "Replacement character (�)",
339
+ 0x1d173: "Musical symbol begin beam (invisible)",
340
+ 0x1d174: "Musical symbol end beam (invisible)",
341
+ 0x1d175: "Musical symbol begin tie (invisible)",
342
+ 0x1d176: "Musical symbol end tie (invisible)",
343
+ 0x1d177: "Musical symbol begin slur (invisible)",
344
+ 0x1d178: "Musical symbol end slur (invisible)",
345
+ 0x1d179: "Musical symbol begin phrase (invisible)",
346
+ 0x1d17a: "Musical symbol end phrase (invisible)",
258
347
  0xe0001: "Language tag",
259
348
  0xe0020: "Tag space",
260
349
  0xe007f: "Cancel tag",
@@ -276,6 +365,13 @@ export function codepointName(cp) {
276
365
  return "Control character (C0)";
277
366
  if (cp >= 0x80 && cp <= 0x9f)
278
367
  return "Control character (C1)";
368
+ const ch = String.fromCodePoint(cp);
369
+ if (PRIVATE_USE.test(ch))
370
+ return "Private-use character";
371
+ if (NONCHARACTER.test(ch))
372
+ return "Noncharacter";
373
+ if (IGNORABLE.test(ch))
374
+ return "Invisible format character";
279
375
  return `Character ${formatCodepoint(cp)}`;
280
376
  }
281
377
  const NOTES = {
@@ -290,6 +386,9 @@ const NOTES = {
290
386
  0x202e: "Reorders displayed text; used in spoofing attacks",
291
387
  0x2014: "Frequently cited as an AI typography tell",
292
388
  0x180e: "Renders invisibly in modern fonts",
389
+ 0x2800: "Looks like a space; a popular invisible filler outside Braille text",
390
+ 0xfffd: "The original character was lost in an encoding error and can't be recovered; check the source",
391
+ 0x2062: "Invisible math operator; no visible glyph in prose",
293
392
  };
294
393
  function codepointNote(cp) {
295
394
  const note = NOTES[cp];
@@ -302,6 +401,9 @@ function codepointNote(cp) {
302
401
  }
303
402
  if (isVariationSelector(cp))
304
403
  return "Invisible; can encode hidden data after ordinary characters";
404
+ const ch = String.fromCodePoint(cp);
405
+ if (PRIVATE_USE.test(ch))
406
+ return "Only displays with the font that defined it; shows as a box elsewhere";
305
407
  return undefined;
306
408
  }
307
409
  const EMOJI_KEPT_NOTE = "Part of an emoji sequence — kept so your emoji don't break";
@@ -461,7 +563,7 @@ function isCategoryEnabled(category, cp, o) {
461
563
  case "invisible":
462
564
  // ZWNJ/ZWJ carry meaning in Persian and Indic scripts, so they get their
463
565
  // own switch; it falls back to removeInvisibleChars for older callers.
464
- if (cp === 0x200c || cp === ZWJ) {
566
+ if (isScriptJoinControl(cp)) {
465
567
  return (o.removeJoinControls ?? !!o.removeInvisibleChars) || ascii;
466
568
  }
467
569
  return !!o.removeInvisibleChars || ascii;
@@ -537,6 +639,11 @@ function runCharacterPass(text, o) {
537
639
  outParts.push(ch);
538
640
  continue;
539
641
  }
642
+ if (info.disposition === "flag") {
643
+ record(cp, info.category, "kept", false);
644
+ outParts.push(ch);
645
+ continue;
646
+ }
540
647
  if (info.disposition === "remove") {
541
648
  record(cp, info.category, "removed", false);
542
649
  }
@@ -873,12 +980,155 @@ function plainAsciiStage(text) {
873
980
  .replace(/\p{M}/gu, "")
874
981
  .replace(/[^\t\n\x20-\x7E]/g, "");
875
982
  }
983
+ /**
984
+ * Pull the display name out of a ChatGPT entity marker body such as
985
+ * ["city","Paris","capital of France"] — the second string is what the
986
+ * answer showed as a link.
987
+ */
988
+ function entityDisplayName(body) {
989
+ const strings = body.match(/"((?:[^"\\]|\\.)*)"/g);
990
+ if (!strings || strings.length === 0)
991
+ return "";
992
+ const pick = strings.length > 1 ? strings[1] : strings[0];
993
+ return pick.slice(1, -1).replace(/\\(.)/g, "$1");
994
+ }
995
+ const CHAT_ARTIFACT_RULES = [
996
+ {
997
+ // U+E200 <kind> U+E202 <payload> U+E201 — ChatGPT's private-use citation,
998
+ // entity and widget markers. Entities keep their visible name.
999
+ label: "U+E200…U+E201",
1000
+ name: "ChatGPT citation or entity marker",
1001
+ note: "Private-use markers ChatGPT uses for sources and links; they show as boxes or text like \"cite turn0search0\" when pasted",
1002
+ pattern: /\uE200([a-z_]+)\uE202([\s\S]*?)\uE201/g,
1003
+ replace: (_m, kind, payload) => (kind === "entity" ? entityDisplayName(payload) : ""),
1004
+ },
1005
+ {
1006
+ label: "oaicite",
1007
+ name: "ChatGPT content reference (oaicite)",
1008
+ note: "Citation placeholder from ChatGPT answers, e.g. :contentReference[oaicite:0]{index=0}",
1009
+ pattern: /[ \t]?:?contentReference\[oaicite:\d+\](?:\{index=\d+\})?/g,
1010
+ replace: () => "",
1011
+ },
1012
+ {
1013
+ label: "【†】",
1014
+ name: "ChatGPT source marker",
1015
+ note: "Citation marker from ChatGPT file and browsing answers, e.g. 【4†source】",
1016
+ pattern: /[ \t]?【\d+(?::\d+)?†[^】\n]{0,40}】/g,
1017
+ replace: () => "",
1018
+ },
1019
+ {
1020
+ // The same citations after the private-use delimiters were stripped by
1021
+ // another app: "citeturn0search0turn0news2".
1022
+ label: "citeturn",
1023
+ name: "ChatGPT citation marker (flattened)",
1024
+ note: "What ChatGPT's citation marker becomes when the invisible delimiters are lost",
1025
+ pattern: /[ \t]?\b(?:file)?cite(?:turn\d+[a-z]+\d+)+/g,
1026
+ replace: () => "",
1027
+ },
1028
+ {
1029
+ label: "entity[…]",
1030
+ name: "ChatGPT entity marker (flattened)",
1031
+ note: "A linked name from a ChatGPT answer that lost its invisible delimiters; the name is kept",
1032
+ pattern: /\bentity(\["[^\]\n]{1,300}\])/g,
1033
+ replace: (_m, body) => entityDisplayName(body),
1034
+ },
1035
+ ];
1036
+ function stripChatArtifactsStage(text) {
1037
+ const rows = [];
1038
+ let out = text;
1039
+ for (const rule of CHAT_ARTIFACT_RULES) {
1040
+ let count = 0;
1041
+ out = out.replace(rule.pattern, (...args) => {
1042
+ count++;
1043
+ const groups = args.slice(1, -2);
1044
+ return rule.replace(args[0], ...groups);
1045
+ });
1046
+ if (count > 0) {
1047
+ rows.push({ codepoint: rule.label, name: rule.name, count, category: "chat-artifact", action: "removed", note: rule.note });
1048
+ }
1049
+ }
1050
+ return { out, rows };
1051
+ }
876
1052
  /* ------------------------------------------------------------------ */
877
- /* Public API */
1053
+ /* Hidden message decoding */
878
1054
  /* ------------------------------------------------------------------ */
1055
+ const HIDDEN_MESSAGE_LIMIT = 500;
1056
+ function utf8Decode(bytes) {
1057
+ try {
1058
+ return decodeURIComponent(bytes.map((b) => "%" + b.toString(16).padStart(2, "0")).join(""));
1059
+ }
1060
+ catch {
1061
+ return null;
1062
+ }
1063
+ }
1064
+ function isReadable(text) {
1065
+ if (text.trim().length === 0)
1066
+ return false;
1067
+ const printable = Array.from(text).filter((c) => /[\p{L}\p{N}\p{P}\p{S}\p{Zs}\n\t]/u.test(c)).length;
1068
+ return printable / Array.from(text).length >= 0.9;
1069
+ }
1070
+ /**
1071
+ * Decodes the two known ways of hiding text in invisible characters:
1072
+ * runs of Unicode tag characters that spell ASCII (outside real emoji flag
1073
+ * sequences), and "emoji smuggling", where each byte of a UTF-8 message is a
1074
+ * variation selector (U+FE00–U+FE0F for 0–15, U+E0100–U+E01EF for 16–255).
1075
+ */
1076
+ export function findHiddenMessages(text) {
1077
+ const cps = Array.from(text, (c) => c.codePointAt(0));
1078
+ const found = [];
1079
+ let i = 0;
1080
+ while (i < cps.length) {
1081
+ const cp = cps[i];
1082
+ if (cp >= 0xe0020 && cp <= 0xe007e) {
1083
+ let j = i;
1084
+ while (j < cps.length && cps[j] >= 0xe0020 && cps[j] <= 0xe007e)
1085
+ j++;
1086
+ // A subdivision flag is U+1F3F4, lowercase tag letters, then CANCEL TAG.
1087
+ const isFlag = i > 0 && cps[i - 1] === BLACK_FLAG && cps[j] === CANCEL_TAG;
1088
+ if (!isFlag) {
1089
+ const decoded = String.fromCharCode(...cps.slice(i, j).map((c) => c - 0xe0000));
1090
+ if (isReadable(decoded)) {
1091
+ found.push({ kind: "tag", text: decoded.slice(0, HIDDEN_MESSAGE_LIMIT), carriers: j - i });
1092
+ }
1093
+ }
1094
+ i = j;
1095
+ continue;
1096
+ }
1097
+ if (isVariationSelector(cp)) {
1098
+ let j = i;
1099
+ const bytes = [];
1100
+ while (j < cps.length && isVariationSelector(cps[j])) {
1101
+ const v = cps[j];
1102
+ bytes.push(v <= 0xfe0f ? v - 0xfe00 : v - 0xe0100 + 16);
1103
+ j++;
1104
+ }
1105
+ // One selector is ordinary emoji styling; a message needs at least two bytes.
1106
+ if (j - i >= 2) {
1107
+ const decoded = utf8Decode(bytes);
1108
+ if (decoded !== null && isReadable(decoded)) {
1109
+ found.push({ kind: "variation-selector", text: decoded.slice(0, HIDDEN_MESSAGE_LIMIT), carriers: j - i });
1110
+ }
1111
+ }
1112
+ i = j;
1113
+ continue;
1114
+ }
1115
+ i++;
1116
+ }
1117
+ return found;
1118
+ }
879
1119
  export function cleanText(text, options) {
880
1120
  const o = options ?? {};
881
1121
  const normalizationRows = [];
1122
+ const hiddenMessages = findHiddenMessages(text);
1123
+ // Stage 0 — AI chat citation markers. Runs before the character pass,
1124
+ // which would otherwise delete their private-use delimiters and leave the
1125
+ // visible "citeturn0search0" text behind.
1126
+ const artifactRows = [];
1127
+ if (o.removeChatArtifacts) {
1128
+ const artifacts = stripChatArtifactsStage(text);
1129
+ text = artifacts.out;
1130
+ artifactRows.push(...artifacts.rows);
1131
+ }
882
1132
  // A soft hyphen at a line end marks a word the PDF split across two lines.
883
1133
  // Stage 1 would delete it and leave "hyph" + newline + "enation", so when
884
1134
  // lines are being joined, rejoin those words first.
@@ -1018,6 +1268,7 @@ export function cleanText(text, options) {
1018
1268
  note: codepointNote(cp),
1019
1269
  });
1020
1270
  }
1271
+ detections.push(...artifactRows);
1021
1272
  detections.push(...normalizationRows);
1022
1273
  // Most frequent first; on a tie, character findings outrank formatting ones.
1023
1274
  const rank = (d) => (d.category === "normalization" ? 1 : 0);
@@ -1053,6 +1304,7 @@ export function cleanText(text, options) {
1053
1304
  stats.quotesDashesNormalized += d.count;
1054
1305
  break;
1055
1306
  case "ai-artifact":
1307
+ case "chat-artifact":
1056
1308
  case "tag":
1057
1309
  case "variation-selector":
1058
1310
  stats.aiArtifactsRemoved += d.count;
@@ -1066,7 +1318,7 @@ export function cleanText(text, options) {
1066
1318
  break;
1067
1319
  }
1068
1320
  }
1069
- return { cleanedText: cleaned, stats, detections };
1321
+ return { cleanedText: cleaned, stats, detections, hiddenMessages };
1070
1322
  }
1071
1323
  /**
1072
1324
  * Scans text for hidden characters and AI watermark artifacts without
@@ -1078,3 +1330,4 @@ export function cleanText(text, options) {
1078
1330
  export function detectHiddenCharacters(text) {
1079
1331
  return cleanText(text, PRESETS[DEFAULT_PRESET]).detections.filter((d) => d.action !== "kept" && d.category !== "typography" && d.category !== "normalization");
1080
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.1.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",