inkbone 0.0.0-stage → 2.0.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.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +318 -0
  3. package/README.md +333 -2
  4. package/bin/inkbone.mjs +941 -0
  5. package/configs/genres.json +570 -0
  6. package/configs/messages.json +302 -0
  7. package/configs/platforms.json +62 -0
  8. package/configs/presets.json +265 -0
  9. package/configs/severity.json +52 -0
  10. package/configs/zh-linguistics.json +986 -0
  11. package/configs/zh-traditional.json +97 -0
  12. package/examples/claude-code-hooks.json +15 -0
  13. package/examples/mcp-config.json +12 -0
  14. package/package.json +61 -4
  15. package/prompts/00-style-architect.md +42 -0
  16. package/prompts/01-beat-planner.md +54 -0
  17. package/prompts/02-paratactic-renderer.md +60 -0
  18. package/prompts/03-targeted-rewriter.md +39 -0
  19. package/prompts/04-evidence-reviewer.md +39 -0
  20. package/prompts/05-reader-simulator.md +54 -0
  21. package/prompts/06-ledger-importer.md +41 -0
  22. package/prompts/07-chapter-settler.md +66 -0
  23. package/resources/bad_vs_good_cases.md +98 -0
  24. package/resources/eval/blind-read-instructions.md +18 -0
  25. package/resources/genre_playbooks/classical-xianxia.md +22 -0
  26. package/resources/genre_playbooks/general-clean.md +19 -0
  27. package/resources/genre_playbooks/historical-court.md +21 -0
  28. package/resources/genre_playbooks/light-fantasy.md +21 -0
  29. package/resources/genre_playbooks/mystery-thriller.md +22 -0
  30. package/resources/genre_playbooks/romance-emotional.md +20 -0
  31. package/resources/genre_playbooks/scifi-wasteland.md +21 -0
  32. package/resources/genre_playbooks/urban-realism.md +22 -0
  33. package/resources/genre_playbooks/wuxia-jianghu.md +21 -0
  34. package/resources/micro_techniques.md +77 -0
  35. package/skills/inkbone/LICENSE +21 -0
  36. package/skills/inkbone/README.md +334 -0
  37. package/skills/inkbone/SKILL.md +155 -0
  38. package/skills/inkbone/benchmarks/eval-set/README.md +49 -0
  39. package/skills/inkbone/benchmarks/eval-set/public-pairs.json +42 -0
  40. package/skills/inkbone/benchmarks/eval-set/seeds.json +42 -0
  41. package/skills/inkbone/bin/inkbone.mjs +941 -0
  42. package/skills/inkbone/configs/genres.json +570 -0
  43. package/skills/inkbone/configs/messages.json +302 -0
  44. package/skills/inkbone/configs/platforms.json +62 -0
  45. package/skills/inkbone/configs/presets.json +265 -0
  46. package/skills/inkbone/configs/severity.json +52 -0
  47. package/skills/inkbone/configs/zh-linguistics.json +986 -0
  48. package/skills/inkbone/configs/zh-traditional.json +97 -0
  49. package/skills/inkbone/package.json +63 -0
  50. package/skills/inkbone/prompts/00-style-architect.md +42 -0
  51. package/skills/inkbone/prompts/01-beat-planner.md +54 -0
  52. package/skills/inkbone/prompts/02-paratactic-renderer.md +60 -0
  53. package/skills/inkbone/prompts/03-targeted-rewriter.md +39 -0
  54. package/skills/inkbone/prompts/04-evidence-reviewer.md +39 -0
  55. package/skills/inkbone/prompts/05-reader-simulator.md +54 -0
  56. package/skills/inkbone/prompts/06-ledger-importer.md +41 -0
  57. package/skills/inkbone/prompts/07-chapter-settler.md +66 -0
  58. package/skills/inkbone/resources/bad_vs_good_cases.md +98 -0
  59. package/skills/inkbone/resources/eval/blind-read-instructions.md +18 -0
  60. package/skills/inkbone/resources/genre_playbooks/classical-xianxia.md +22 -0
  61. package/skills/inkbone/resources/genre_playbooks/general-clean.md +19 -0
  62. package/skills/inkbone/resources/genre_playbooks/historical-court.md +21 -0
  63. package/skills/inkbone/resources/genre_playbooks/light-fantasy.md +21 -0
  64. package/skills/inkbone/resources/genre_playbooks/mystery-thriller.md +22 -0
  65. package/skills/inkbone/resources/genre_playbooks/romance-emotional.md +20 -0
  66. package/skills/inkbone/resources/genre_playbooks/scifi-wasteland.md +21 -0
  67. package/skills/inkbone/resources/genre_playbooks/urban-realism.md +22 -0
  68. package/skills/inkbone/resources/genre_playbooks/wuxia-jianghu.md +21 -0
  69. package/skills/inkbone/resources/micro_techniques.md +77 -0
  70. package/skills/inkbone/src/auditor.mjs +24 -0
  71. package/skills/inkbone/src/benchmark-runner.mjs +71 -0
  72. package/skills/inkbone/src/boundary-compiler.mjs +54 -0
  73. package/skills/inkbone/src/browser-doctor.mjs +30 -0
  74. package/skills/inkbone/src/calibrator.mjs +175 -0
  75. package/skills/inkbone/src/config-loader.mjs +233 -0
  76. package/skills/inkbone/src/continuity.mjs +5 -0
  77. package/skills/inkbone/src/core/auditor.mjs +914 -0
  78. package/skills/inkbone/src/core/boundary-compiler.mjs +423 -0
  79. package/skills/inkbone/src/core/browser-doctor.mjs +318 -0
  80. package/skills/inkbone/src/core/config-compiler.mjs +434 -0
  81. package/skills/inkbone/src/core/continuity.mjs +158 -0
  82. package/skills/inkbone/src/core/evidence-validator.mjs +77 -0
  83. package/skills/inkbone/src/core/exporter.mjs +128 -0
  84. package/skills/inkbone/src/core/formatter.mjs +241 -0
  85. package/skills/inkbone/src/core/ledger-manager.mjs +576 -0
  86. package/skills/inkbone/src/core/normalizer.mjs +517 -0
  87. package/skills/inkbone/src/core/profiler.mjs +686 -0
  88. package/skills/inkbone/src/core/rule-engine.mjs +1536 -0
  89. package/skills/inkbone/src/core/style-profiler.mjs +229 -0
  90. package/skills/inkbone/src/detector.mjs +270 -0
  91. package/skills/inkbone/src/doctor.mjs +428 -0
  92. package/skills/inkbone/src/evaluation.mjs +311 -0
  93. package/skills/inkbone/src/evidence-validator.mjs +15 -0
  94. package/skills/inkbone/src/exporter.mjs +106 -0
  95. package/skills/inkbone/src/formatter.mjs +34 -0
  96. package/skills/inkbone/src/importer.mjs +230 -0
  97. package/skills/inkbone/src/index.mjs +116 -0
  98. package/skills/inkbone/src/ledger-manager.mjs +15 -0
  99. package/skills/inkbone/src/mcp-server.mjs +861 -0
  100. package/skills/inkbone/src/normalizer.mjs +73 -0
  101. package/skills/inkbone/src/profiler.mjs +17 -0
  102. package/skills/inkbone/src/rule-engine.mjs +73 -0
  103. package/skills/inkbone/src/rule-stats.mjs +142 -0
  104. package/skills/inkbone/src/style-profiler.mjs +25 -0
  105. package/src/auditor.mjs +24 -0
  106. package/src/benchmark-runner.mjs +71 -0
  107. package/src/boundary-compiler.mjs +54 -0
  108. package/src/browser-doctor.mjs +30 -0
  109. package/src/calibrator.mjs +175 -0
  110. package/src/config-loader.mjs +233 -0
  111. package/src/continuity.mjs +5 -0
  112. package/src/core/auditor.mjs +914 -0
  113. package/src/core/boundary-compiler.mjs +423 -0
  114. package/src/core/browser-doctor.mjs +318 -0
  115. package/src/core/config-compiler.mjs +434 -0
  116. package/src/core/continuity.mjs +158 -0
  117. package/src/core/evidence-validator.mjs +77 -0
  118. package/src/core/exporter.mjs +128 -0
  119. package/src/core/formatter.mjs +241 -0
  120. package/src/core/ledger-manager.mjs +576 -0
  121. package/src/core/normalizer.mjs +517 -0
  122. package/src/core/profiler.mjs +686 -0
  123. package/src/core/rule-engine.mjs +1536 -0
  124. package/src/core/style-profiler.mjs +229 -0
  125. package/src/detector.mjs +270 -0
  126. package/src/doctor.mjs +428 -0
  127. package/src/evaluation.mjs +311 -0
  128. package/src/evidence-validator.mjs +15 -0
  129. package/src/exporter.mjs +106 -0
  130. package/src/formatter.mjs +34 -0
  131. package/src/importer.mjs +230 -0
  132. package/src/index.mjs +116 -0
  133. package/src/ledger-manager.mjs +15 -0
  134. package/src/mcp-server.mjs +861 -0
  135. package/src/normalizer.mjs +73 -0
  136. package/src/profiler.mjs +17 -0
  137. package/src/rule-engine.mjs +73 -0
  138. package/src/rule-stats.mjs +142 -0
  139. package/src/style-profiler.mjs +25 -0
@@ -0,0 +1,1536 @@
1
+ // 规则扫描引擎:统一承接书级字面量白名单、单行安全引号遮蔽、密度门槛、必改/提示分级、修辞与退化检测
2
+
3
+ const LAYER_RANK = { project: 3, genre: 2, universal: 1 };
4
+
5
+ // 统计可见字符(汉字与字母数字,具体字符类由 JSON 配置提供)
6
+ export function countVisibleChars(text, visibleCharRegex) {
7
+ if (!text) return 0;
8
+ const matched = text.match(visibleCharRegex);
9
+ return matched ? matched.length : 0;
10
+ }
11
+
12
+ // 书级字面量白名单等长空格遮罩(仅用于规则与句式扫描,不影响字数和统计指纹)
13
+ export function maskWhitelistLiterals(
14
+ text,
15
+ whitelistLiterals = [],
16
+ maskChar = " "
17
+ ) {
18
+ if (!text || !whitelistLiterals || whitelistLiterals.length === 0) {
19
+ return text;
20
+ }
21
+ const sorted = [...whitelistLiterals].sort((a, b) => b.length - a.length);
22
+ const chars = text.split("");
23
+ for (const literal of sorted) {
24
+ if (!literal) continue;
25
+ let idx = text.indexOf(literal);
26
+ while (idx !== -1) {
27
+ for (let i = idx; i < idx + literal.length; i += 1) {
28
+ chars[i] = maskChar;
29
+ }
30
+ idx = text.indexOf(literal, idx + literal.length);
31
+ }
32
+ }
33
+ return chars.join("");
34
+ }
35
+
36
+ // 提取单行内成对引号的 [start, end) 区间
37
+ export function getQuotedRanges(text, quoteMaskRegexes = []) {
38
+ const ranges = [];
39
+ for (const re of quoteMaskRegexes) {
40
+ re.lastIndex = 0;
41
+ let match;
42
+ while ((match = re.exec(text)) !== null) {
43
+ if (match[0].length === 0) {
44
+ re.lastIndex += 1;
45
+ continue;
46
+ }
47
+ ranges.push([match.index, match.index + match[0].length]);
48
+ }
49
+ }
50
+ return ranges.sort((a, b) => a[0] - b[0]);
51
+ }
52
+
53
+ // 把成对引号内片段等长遮罩为中性占位符以保留列号;可选把行末未闭合开引号也遮到行尾
54
+ export function maskQuotedText(
55
+ text,
56
+ quoteMaskRegexes = [],
57
+ maskChar = "?",
58
+ unclosedQuoteStart = null
59
+ ) {
60
+ if (!text) return text;
61
+ let out = text;
62
+ for (const re of quoteMaskRegexes) {
63
+ re.lastIndex = 0;
64
+ out = out.replace(re, (match) => maskChar.repeat(match.length));
65
+ }
66
+ if (unclosedQuoteStart) {
67
+ const m = unclosedQuoteStart.exec(out);
68
+ if (m) {
69
+ out = out.slice(0, m.index) + maskChar.repeat(out.length - m.index);
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+
75
+ // 从单段文本中剥离真正的说话对白(区分弯双引号对白与直角引号书名/器物强调)
76
+ export function stripSpokenDialogue(text, lingConfig, replacement = "") {
77
+ const src = String(text || "");
78
+ const spanRe = lingConfig?.compiledRegex?.dialogueSpanGlobal;
79
+ if (!src || !spanRe) {
80
+ return {
81
+ narration: src,
82
+ hasSpokenDialogue: false,
83
+ spokenChars: 0,
84
+ isPureDialogue: false,
85
+ };
86
+ }
87
+ const cornerCfg = lingConfig.compiledRegex.cornerQuoteDialogue || null;
88
+ spanRe.lastIndex = 0;
89
+ const spans = [];
90
+ let match;
91
+ while ((match = spanRe.exec(src)) !== null) {
92
+ if (match[0].length === 0) {
93
+ spanRe.lastIndex += 1;
94
+ continue;
95
+ }
96
+ spans.push({
97
+ start: match.index,
98
+ end: match.index + match[0].length,
99
+ raw: match[0],
100
+ });
101
+ }
102
+ if (spans.length === 0) {
103
+ return {
104
+ narration: src,
105
+ hasSpokenDialogue: false,
106
+ spokenChars: 0,
107
+ isPureDialogue: false,
108
+ };
109
+ }
110
+
111
+ // 整段只由引号片段构成时,即使使用直角引号也按纯对白段处理
112
+ let nonSpanText = "";
113
+ let pos = 0;
114
+ for (const sp of spans) {
115
+ nonSpanText += src.slice(pos, sp.start);
116
+ pos = sp.end;
117
+ }
118
+ nonSpanText += src.slice(pos);
119
+ const wholeLineQuoted = nonSpanText.trim().length === 0;
120
+
121
+ let out = "";
122
+ let cursor = 0;
123
+ let spokenChars = 0;
124
+ let hasSpokenDialogue = false;
125
+ for (const sp of spans) {
126
+ const openChar = sp.raw[0];
127
+ let isDialogue = true;
128
+ if (cornerCfg && cornerCfg.cornerChars.has(openChar) && !wholeLineQuoted) {
129
+ const inner = sp.raw.slice(1, -1);
130
+ const before = src.slice(Math.max(0, sp.start - 8), sp.start);
131
+ const hasPunct = cornerCfg.innerPunctRegex
132
+ ? cornerCfg.innerPunctRegex.test(inner)
133
+ : false;
134
+ const hasLead = cornerCfg.leadSpeechRegex
135
+ ? cornerCfg.leadSpeechRegex.test(before)
136
+ : false;
137
+ isDialogue = hasPunct || hasLead;
138
+ }
139
+ if (isDialogue) {
140
+ out += src.slice(cursor, sp.start) + replacement;
141
+ cursor = sp.end;
142
+ spokenChars += sp.raw.length;
143
+ hasSpokenDialogue = true;
144
+ }
145
+ }
146
+ out += src.slice(cursor);
147
+ const isPureDialogue = hasSpokenDialogue && out.trim().length === 0;
148
+ return { narration: out, hasSpokenDialogue, spokenChars, isPureDialogue };
149
+ }
150
+
151
+ // 同一段落内被更长命中完全包住的短命中只保留最长的一条;同长撞车按 project > genre > universal 保留
152
+ export function dedupContainedHits(hits) {
153
+ return hits.filter((a) => {
154
+ const aLen = a.end - a.start;
155
+ return !hits.some((b) => {
156
+ if (b === a) return false;
157
+ const bLen = b.end - b.start;
158
+ if (b.start <= a.start && b.end >= a.end) {
159
+ if (bLen > aLen) return true;
160
+ if (bLen === aLen) {
161
+ const rankA = LAYER_RANK[a.layer] || 0;
162
+ const rankB = LAYER_RANK[b.layer] || 0;
163
+ if (rankB > rankA) return true;
164
+ if (rankB === rankA && hits.indexOf(b) < hits.indexOf(a)) return true;
165
+ }
166
+ }
167
+ return false;
168
+ });
169
+ });
170
+ }
171
+
172
+ // 承接确认语与合成词排除守卫(用于反序对比句等易误报模式,所有字表来自 JSON 配置)
173
+ function passesReverseNotIsGuard(rule, text, match) {
174
+ const start = match.index;
175
+ if (start > 0 && rule.prevExcludeSet && rule.prevExcludeSet.has(text[start - 1])) {
176
+ return false;
177
+ }
178
+ if (rule.secondCharNot && text[start + 1] === rule.secondCharNot) {
179
+ return false;
180
+ }
181
+ if (rule.nextIgnoreRegexObj && match[2] && rule.nextIgnoreRegexObj.test(match[2])) {
182
+ return false;
183
+ }
184
+ if (rule.affirmationParticleSet && rule.affirmationBoundarySet) {
185
+ const nextChar = text[start + 1] || "";
186
+ const afterChar = text[start + 2] || "";
187
+ if (
188
+ rule.affirmationParticleSet.has(nextChar) &&
189
+ rule.affirmationBoundarySet.has(afterChar)
190
+ ) {
191
+ return false;
192
+ }
193
+ }
194
+ return true;
195
+ }
196
+
197
+ // 计算尾窗起始段落索引(从文末往前累加可见字数直到达到 tailWindowChars)
198
+ export function computeTailStartIndex(
199
+ paragraphs,
200
+ tailWindowChars,
201
+ quoteMaskRegexes,
202
+ visibleCharRegex
203
+ ) {
204
+ let acc = 0;
205
+ let startIdx = paragraphs.length;
206
+ for (let i = paragraphs.length - 1; i >= 0 && acc < tailWindowChars; i -= 1) {
207
+ startIdx = i;
208
+ const stripped = maskQuotedText(paragraphs[i].text, quoteMaskRegexes, " ");
209
+ acc += countVisibleChars(stripped, visibleCharRegex);
210
+ }
211
+ return startIdx;
212
+ }
213
+
214
+ // 统一扫描段落数组上的规则集合(支持 scope、tail600 窗口、白名单、引号遮蔽与包含去重)
215
+ export function scanParagraphRuleSet(paragraphs, rules, options = {}) {
216
+ if (!rules || rules.length === 0 || !paragraphs || paragraphs.length === 0) {
217
+ return [];
218
+ }
219
+ const quoteRegexes = options.quoteMaskRegexes || [];
220
+ const quoteMaskChar = options.quoteMaskChar || "?";
221
+ const whitelistLiterals = options.whitelistLiterals || [];
222
+ const whitelistMaskChar = options.whitelistMaskChar || " ";
223
+ const visibleCharRegex = options.visibleCharRegex;
224
+ const tailWindowChars = options.tailWindowChars || 600;
225
+ const tailStartIdx = rules.some((r) => r.window === "tail600")
226
+ ? computeTailStartIndex(
227
+ paragraphs,
228
+ tailWindowChars,
229
+ quoteRegexes,
230
+ visibleCharRegex
231
+ )
232
+ : 0;
233
+
234
+ const allHits = [];
235
+ for (let pIdx = 0; pIdx < paragraphs.length; pIdx += 1) {
236
+ const para = paragraphs[pIdx];
237
+ const wlText = maskWhitelistLiterals(
238
+ para.text,
239
+ whitelistLiterals,
240
+ whitelistMaskChar
241
+ );
242
+ let narrationText = null;
243
+ const rawParaHits = [];
244
+
245
+ for (const rule of rules) {
246
+ if (rule.window === "tail600" && pIdx < tailStartIdx) continue;
247
+ const target =
248
+ rule.scope === "narration"
249
+ ? (narrationText ??= maskQuotedText(wlText, quoteRegexes, quoteMaskChar))
250
+ : wlText;
251
+
252
+ rule.regex.lastIndex = 0;
253
+ let match;
254
+ while ((match = rule.regex.exec(target)) !== null) {
255
+ if (match[0].length === 0) {
256
+ rule.regex.lastIndex += 1;
257
+ continue;
258
+ }
259
+ if (rule.guard === "reverseNotIs" && !passesReverseNotIsGuard(rule, target, match)) {
260
+ continue;
261
+ }
262
+ rawParaHits.push({
263
+ id: rule.id,
264
+ layer: rule.layer || "universal",
265
+ category: rule.category,
266
+ family: rule.family || null,
267
+ line: para.line,
268
+ start: match.index,
269
+ end: match.index + match[0].length,
270
+ matched: para.text.slice(match.index, match.index + match[0].length),
271
+ remedy: rule.remedy,
272
+ });
273
+ }
274
+ }
275
+
276
+ const deduped = dedupContainedHits(rawParaHits).map(
277
+ ({ start: _s, end: _e, ...clean }) => clean
278
+ );
279
+ allHits.push(...deduped);
280
+ }
281
+
282
+ return allHits;
283
+ }
284
+
285
+ // 按密度门槛(minHits / perKilo)过滤,并根据 blockingMinHits * scale 判定必改/提示分级
286
+ export function evaluateHitsWithDensity(
287
+ hits,
288
+ rules,
289
+ totalHan,
290
+ extraFamilyCounts = null
291
+ ) {
292
+ if (!hits || hits.length === 0) {
293
+ return { hits: [], hasBlocking: false };
294
+ }
295
+ const ruleMap = new Map();
296
+ for (const r of rules || []) {
297
+ if (r && r.id) ruleMap.set(r.id, r);
298
+ }
299
+
300
+ const byRule = new Map();
301
+ const familyCounts = new Map(extraFamilyCounts || []);
302
+ for (const h of hits) {
303
+ byRule.set(h.id, (byRule.get(h.id) || 0) + 1);
304
+ const fam = h.family || ruleMap.get(h.id)?.family;
305
+ if (fam) {
306
+ familyCounts.set(fam, (familyCounts.get(fam) || 0) + 1);
307
+ }
308
+ }
309
+
310
+ const kept = [];
311
+ let hasBlocking = false;
312
+ for (const h of hits) {
313
+ const rule = ruleMap.get(h.id) || {};
314
+ const ruleCount = byRule.get(h.id) || 0;
315
+ const minHits = rule.minHits || rule.advisoryMinHits || 1;
316
+ const perKiloMin = rule.perKilo || 0;
317
+ const actualPerKilo = totalHan > 0 ? (ruleCount / totalHan) * 1000 : 0;
318
+
319
+ if (ruleCount < minHits) continue;
320
+ if (perKiloMin > 0 && actualPerKilo < perKiloMin) continue;
321
+
322
+ const unit = rule.scaleUnitChars || 4500;
323
+ const scale = Math.max(
324
+ 1,
325
+ Math.floor((totalHan + Math.floor(unit / 2)) / unit)
326
+ );
327
+ const fam = h.family || rule.family;
328
+ const effectiveCount = fam ? familyCounts.get(fam) || ruleCount : ruleCount;
329
+
330
+ let isBlocking = rule.level === "blocking";
331
+ if (!isBlocking && rule.blockingMinHits) {
332
+ isBlocking = effectiveCount >= rule.blockingMinHits * scale;
333
+ }
334
+
335
+ const level = isBlocking ? "blocking" : "advisory";
336
+ const review = isBlocking ? "mechanical" : rule.review || "semantic";
337
+ if (isBlocking) hasBlocking = true;
338
+
339
+ kept.push({
340
+ ...h,
341
+ level,
342
+ review,
343
+ });
344
+ }
345
+
346
+ return { hits: kept, hasBlocking };
347
+ }
348
+
349
+ // 检查连续三段「不是A / 也不是B / 只是C」跨段工整排比(只发 advisory 语义提示)
350
+ export function scanCrossParagraphParallel(paragraphs, crossCfg, options = {}) {
351
+ if (!crossCfg || !paragraphs || paragraphs.length < 3) return [];
352
+ const quoteRegexes = options.quoteMaskRegexes || [];
353
+ const quoteMaskChar = options.quoteMaskChar || "?";
354
+ const whitelistLiterals = options.whitelistLiterals || [];
355
+ const whitelistMaskChar = options.whitelistMaskChar || " ";
356
+
357
+ const hits = [];
358
+ const win = [];
359
+ for (const para of paragraphs) {
360
+ const wl = maskWhitelistLiterals(
361
+ para.text,
362
+ whitelistLiterals,
363
+ whitelistMaskChar
364
+ );
365
+ const masked = maskQuotedText(wl, quoteRegexes, quoteMaskChar).trim();
366
+ if (win.length > 0 && para.line - win[win.length - 1].line > 2) {
367
+ win.length = 0;
368
+ }
369
+ win.push({ line: para.line, masked, original: para.text });
370
+ if (win.length > 3) win.shift();
371
+ if (win.length !== 3) continue;
372
+
373
+ if (
374
+ crossCfg.startRegexObj.test(win[0].masked) &&
375
+ crossCfg.middleRegexObj.test(win[1].masked) &&
376
+ crossCfg.endRegexObj.test(win[2].masked)
377
+ ) {
378
+ hits.push({
379
+ id: crossCfg.id,
380
+ layer: "universal",
381
+ category: crossCfg.category,
382
+ line: win[0].line,
383
+ matched: win.map((w) => w.original.slice(0, 24)).join(" / "),
384
+ level: "advisory",
385
+ review: crossCfg.review || "semantic",
386
+ remedy: crossCfg.remedy,
387
+ });
388
+ }
389
+ }
390
+ return hits;
391
+ }
392
+
393
+ // 拆分句段辅助
394
+ function splitCleanSentences(text, splitRegex) {
395
+ return text
396
+ .split(splitRegex)
397
+ .map((s) => s.trim())
398
+ .filter(Boolean);
399
+ }
400
+
401
+ // 统计多个词语在字符串中出现的总次数
402
+ function countLiteralTerms(text, terms) {
403
+ let count = 0;
404
+ for (const term of terms || []) {
405
+ if (!term) continue;
406
+ let idx = text.indexOf(term);
407
+ while (idx !== -1) {
408
+ count += 1;
409
+ idx = text.indexOf(term, idx + term.length);
410
+ }
411
+ }
412
+ return count;
413
+ }
414
+
415
+ // 截取命中位置所属句段摘要
416
+ function excerptAround(text, idx, sentenceSplitRegex) {
417
+ const parts = text.split(sentenceSplitRegex);
418
+ let cursor = 0;
419
+ for (const part of parts) {
420
+ const end = cursor + part.length;
421
+ if (idx <= end) return part.trim().slice(0, 36);
422
+ cursor = end + 1;
423
+ }
424
+ return text.slice(Math.max(0, idx - 12), idx + 24).trim();
425
+ }
426
+
427
+ // 运行移植自 oh-story 的密度型文风探针(微动作、套式反应、动作清单、引号强调、电报体反向守卫等)
428
+ export function runDensityTics(
429
+ paragraphs,
430
+ lingConfig,
431
+ whitelistLiterals = [],
432
+ disabledRuleIds = new Set()
433
+ ) {
434
+ const dCfg = lingConfig.compiledRegex.densityRules;
435
+ if (!dCfg || !paragraphs || paragraphs.length === 0) return [];
436
+
437
+ const quoteRegexes = lingConfig.compiledRegex.quoteMaskRegexes || [];
438
+ const unclosedQuoteStart = lingConfig.compiledRegex.unclosedQuoteStart;
439
+ const visibleCharRegex = lingConfig.compiledRegex.visibleCharGlobal;
440
+ const wlMaskChar = lingConfig.tokens.whitelistMaskChar || " ";
441
+ const sentenceSplit =
442
+ lingConfig.compiledRegex.degeneration?.sentenceSplitRegex ||
443
+ lingConfig.compiledRegex.sentenceDelimiter;
444
+
445
+ const tics = [];
446
+
447
+ // 预备每段的白名单遮罩与引号外叙述文本(用空格遮罩保持字符长度不粘连)
448
+ const prepared = paragraphs.map((p) => {
449
+ const wlText = maskWhitelistLiterals(p.text, whitelistLiterals, wlMaskChar);
450
+ const narration = maskQuotedText(wlText, quoteRegexes, " ");
451
+ const narrationLen = countVisibleChars(narration, visibleCharRegex);
452
+ return {
453
+ line: p.line,
454
+ raw: p.text,
455
+ wlText,
456
+ narration,
457
+ narrationLen,
458
+ };
459
+ });
460
+
461
+ const totalNarrationChars = prepared.reduce((acc, p) => acc + p.narrationLen, 0);
462
+
463
+ // 辅助:运行汇总型密度计数规则
464
+ const collectDensityMatches = (cfg, collector) => {
465
+ if (!cfg || disabledRuleIds.has(cfg.id)) return null;
466
+ if (totalNarrationChars === 0) return null;
467
+ let hits = 0;
468
+ let firstLine = null;
469
+ const samples = [];
470
+ for (const item of prepared) {
471
+ const res = collector(item);
472
+ if (res.count > 0) {
473
+ hits += res.count;
474
+ if (firstLine === null) firstLine = item.line;
475
+ for (const s of res.samples || []) {
476
+ if (samples.length < 6 && s && !samples.includes(s)) samples.push(s);
477
+ }
478
+ }
479
+ }
480
+ const perKilo = (hits / totalNarrationChars) * 1000;
481
+ if (hits < (cfg.minHits || 1) || perKilo < (cfg.perKilo || 0)) return null;
482
+ return {
483
+ id: cfg.id,
484
+ layer: "universal",
485
+ category: cfg.id,
486
+ line: firstLine,
487
+ hits,
488
+ perKilo: Number(perKilo.toFixed(1)),
489
+ samples,
490
+ level: "advisory",
491
+ review: cfg.review || "semantic",
492
+ remedy: cfg.remedy,
493
+ };
494
+ };
495
+
496
+ // 1. 微动作补语复读(V了一下/了半圈)
497
+ const microRes = collectDensityMatches(dCfg.microActionTic, (item) => {
498
+ const re = dCfg.microActionTic.regex;
499
+ re.lastIndex = 0;
500
+ let count = 0;
501
+ const samples = [];
502
+ let m;
503
+ while ((m = re.exec(item.narration)) !== null) {
504
+ count += 1;
505
+ samples.push(item.raw.slice(Math.max(0, m.index - 4), m.index + m[0].length));
506
+ }
507
+ return { count, samples };
508
+ });
509
+ if (microRes) tics.push(microRes);
510
+
511
+ // 2. 套式身体反应成片
512
+ const stockRes = collectDensityMatches(dCfg.stockReactionTic, (item) => {
513
+ let count = 0;
514
+ const samples = [];
515
+ for (const re of dCfg.stockReactionTic.regexes) {
516
+ re.lastIndex = 0;
517
+ let m;
518
+ while ((m = re.exec(item.narration)) !== null) {
519
+ count += 1;
520
+ samples.push(excerptAround(item.raw, m.index, sentenceSplit));
521
+ }
522
+ }
523
+ return { count, samples };
524
+ });
525
+ if (stockRes) tics.push(stockRes);
526
+
527
+ // 3. 监控摄像头式动作清单(按段报出)
528
+ if (dCfg.actionListTic && !disabledRuleIds.has(dCfg.actionListTic.id)) {
529
+ const ac = dCfg.actionListTic;
530
+ for (const item of prepared) {
531
+ if (item.narrationLen === 0) continue;
532
+ ac.verbRegex.lastIndex = 0;
533
+ const verbs = [];
534
+ let m;
535
+ while ((m = ac.verbRegex.exec(item.narration)) !== null) {
536
+ verbs.push(m[0]);
537
+ }
538
+ if (verbs.length < ac.minVerbsPerPara) continue;
539
+ const sepMatches = item.narration.match(ac.separatorRegex);
540
+ const sepCount = sepMatches ? sepMatches.length : 0;
541
+ if (sepCount < ac.minSeparatorsPerPara) continue;
542
+ tics.push({
543
+ id: ac.id,
544
+ layer: "universal",
545
+ category: ac.id,
546
+ line: item.line,
547
+ hits: verbs.length,
548
+ samples: verbs.slice(0, 8),
549
+ level: "advisory",
550
+ review: ac.review || "semantic",
551
+ remedy: ac.remedy,
552
+ });
553
+ }
554
+ }
555
+
556
+ // 4. 叙述层短词引号强调滥用(跳过独立台词行、系统面板【】、引语动词邻接短台词、拟声词)
557
+ if (dCfg.quoteEmphasisTic && !disabledRuleIds.has(dCfg.quoteEmphasisTic.id)) {
558
+ const qc = dCfg.quoteEmphasisTic;
559
+ let hits = 0;
560
+ let firstLine = null;
561
+ const samples = [];
562
+ for (const item of prepared) {
563
+ if (item.narrationLen === 0) continue;
564
+ const ranges = getQuotedRanges(item.wlText, quoteRegexes);
565
+ for (const [start, end] of ranges) {
566
+ if (item.wlText[start] === qc.panelOpenChar) continue;
567
+ if (
568
+ ranges.some(
569
+ ([s2, e2]) => s2 <= start && end <= e2 && (s2 !== start || e2 !== end)
570
+ )
571
+ ) {
572
+ continue;
573
+ }
574
+ const inner = item.wlText.slice(start + 1, end - 1);
575
+ const vis = countVisibleChars(inner, visibleCharRegex);
576
+ if (vis < 1 || vis > qc.maxVisibleHan) continue;
577
+ if (qc.punctuationInsideRegex.test(inner)) continue;
578
+ const before = item.wlText.slice(Math.max(0, start - 8), start);
579
+ const after = item.wlText.slice(end, end + 6);
580
+ if (qc.speechVerbRegex.test(before) || qc.speechVerbRegex.test(after)) {
581
+ continue;
582
+ }
583
+ if (qc.onomatopoeiaSuffixRegex.test(after)) continue;
584
+ hits += 1;
585
+ if (firstLine === null) firstLine = item.line;
586
+ if (samples.length < 6 && !samples.includes(inner)) samples.push(inner);
587
+ }
588
+ }
589
+ if (hits >= qc.minHits) {
590
+ tics.push({
591
+ id: qc.id,
592
+ layer: "universal",
593
+ category: qc.id,
594
+ line: firstLine,
595
+ hits,
596
+ samples,
597
+ level: "advisory",
598
+ review: qc.review || "semantic",
599
+ remedy: qc.remedy,
600
+ });
601
+ }
602
+ }
603
+
604
+ // 5. 比喻密度
605
+ const metaRes = collectDensityMatches(dCfg.metaphorDensityTic, (item) => {
606
+ const mc = dCfg.metaphorDensityTic;
607
+ let count = 0;
608
+ const samples = [];
609
+ mc.markerRegex.lastIndex = 0;
610
+ let m;
611
+ while ((m = mc.markerRegex.exec(item.narration)) !== null) {
612
+ count += 1;
613
+ samples.push(excerptAround(item.raw, m.index, sentenceSplit));
614
+ }
615
+ mc.likePhraseRegex.lastIndex = 0;
616
+ while ((m = mc.likePhraseRegex.exec(item.narration)) !== null) {
617
+ const prefix = item.narration.slice(Math.max(0, m.index - 8), m.index);
618
+ if (mc.prefixGuardRegex.test(prefix)) continue;
619
+ count += 1;
620
+ samples.push(excerptAround(item.raw, m.index, sentenceSplit));
621
+ }
622
+ return { count, samples };
623
+ });
624
+ if (metaRes) tics.push(metaRes);
625
+
626
+ // 6. 抽象总结复读
627
+ const absRes = collectDensityMatches(dCfg.abstractSummaryTic, (item) => {
628
+ let count = 0;
629
+ const samples = [];
630
+ for (const re of dCfg.abstractSummaryTic.regexes) {
631
+ re.lastIndex = 0;
632
+ let m;
633
+ while ((m = re.exec(item.narration)) !== null) {
634
+ count += 1;
635
+ samples.push(m[0]);
636
+ }
637
+ }
638
+ return { count, samples };
639
+ });
640
+ if (absRes) tics.push(absRes);
641
+
642
+ // 7. 论文式解释推理链
643
+ if (dCfg.reasoningChainTic && !disabledRuleIds.has(dCfg.reasoningChainTic.id)) {
644
+ const rc = dCfg.reasoningChainTic;
645
+ let hits = 0;
646
+ let coreHits = 0;
647
+ let linkHits = 0;
648
+ let firstLine = null;
649
+ const samples = [];
650
+ const buckets = new Set();
651
+
652
+ for (const item of prepared) {
653
+ if (item.narrationLen === 0) continue;
654
+ const accepted = [];
655
+ for (const pObj of rc.compiledPatterns) {
656
+ pObj.regex.lastIndex = 0;
657
+ let m;
658
+ while ((m = pObj.regex.exec(item.narration)) !== null) {
659
+ const s = m.index;
660
+ const e = s + m[0].length;
661
+ if (accepted.some(([a, b]) => s < b && e > a)) continue;
662
+ accepted.push([s, e]);
663
+ hits += 1;
664
+ if (pObj.core) coreHits += 1;
665
+ if (pObj.key === "connector" || pObj.key === "modal") linkHits += 1;
666
+ buckets.add(pObj.key);
667
+ if (firstLine === null) firstLine = item.line;
668
+ if (samples.length < 8 && !samples.includes(m[0])) samples.push(m[0]);
669
+ }
670
+ }
671
+ }
672
+
673
+ const perKilo =
674
+ totalNarrationChars > 0 ? (hits / totalNarrationChars) * 1000 : 0;
675
+ if (
676
+ totalNarrationChars > 0 &&
677
+ hits >= rc.minHits &&
678
+ coreHits >= rc.minCoreHits &&
679
+ linkHits >= rc.minLinkHits &&
680
+ buckets.size >= rc.minBuckets &&
681
+ perKilo >= rc.perKilo
682
+ ) {
683
+ tics.push({
684
+ id: rc.id,
685
+ layer: "universal",
686
+ category: rc.id,
687
+ line: firstLine,
688
+ hits,
689
+ perKilo: Number(perKilo.toFixed(1)),
690
+ samples,
691
+ level: "advisory",
692
+ review: rc.review || "semantic",
693
+ remedy: rc.remedy,
694
+ });
695
+ }
696
+ }
697
+
698
+ // 8. 叙述旁白省略号刷屏
699
+ if (dCfg.ellipsisDensityTic && !disabledRuleIds.has(dCfg.ellipsisDensityTic.id)) {
700
+ const ec = dCfg.ellipsisDensityTic;
701
+ let hits = 0;
702
+ let chars = 0;
703
+ let firstLine = null;
704
+ const samples = [];
705
+ for (const item of prepared) {
706
+ const safeNarration = maskQuotedText(
707
+ item.wlText,
708
+ quoteRegexes,
709
+ " ",
710
+ unclosedQuoteStart
711
+ );
712
+ chars += countVisibleChars(safeNarration, visibleCharRegex);
713
+ ec.regex.lastIndex = 0;
714
+ let m;
715
+ while ((m = ec.regex.exec(safeNarration)) !== null) {
716
+ hits += 1;
717
+ if (firstLine === null) firstLine = item.line;
718
+ if (samples.length < 4) {
719
+ samples.push(
720
+ item.raw.slice(Math.max(0, m.index - 8), m.index + m[0].length + 4).trim()
721
+ );
722
+ }
723
+ }
724
+ }
725
+ const perKilo = chars > 0 ? (hits / chars) * 1000 : 0;
726
+ if (chars > 0 && hits >= ec.minHits && perKilo >= ec.perKilo) {
727
+ tics.push({
728
+ id: ec.id,
729
+ layer: "universal",
730
+ category: ec.id,
731
+ line: firstLine,
732
+ hits,
733
+ perKilo: Number(perKilo.toFixed(1)),
734
+ samples,
735
+ level: "advisory",
736
+ review: ec.review || "semantic",
737
+ remedy: ec.remedy,
738
+ });
739
+ }
740
+ }
741
+
742
+ // 8b. 叙述层感叹号密度(精修稿 ~0-0.7/千字,滑稿可到 7-17/千字)与连叠(一处即报)
743
+ const exclRes = collectDensityMatches(dCfg.exclamationDensityTic, (item) => {
744
+ const re = dCfg.exclamationDensityTic.regex;
745
+ re.lastIndex = 0;
746
+ let count = 0;
747
+ const samples = [];
748
+ let m;
749
+ while ((m = re.exec(item.narration)) !== null) {
750
+ count += 1;
751
+ samples.push(
752
+ item.raw.slice(Math.max(0, m.index - 10), m.index + m[0].length + 2).trim()
753
+ );
754
+ }
755
+ return { count, samples };
756
+ });
757
+ if (exclRes) tics.push(exclRes);
758
+
759
+ const stackRes = collectDensityMatches(dCfg.exclamationStackTic, (item) => {
760
+ const re = dCfg.exclamationStackTic.regex;
761
+ re.lastIndex = 0;
762
+ let count = 0;
763
+ const samples = [];
764
+ let m;
765
+ while ((m = re.exec(item.narration)) !== null) {
766
+ count += 1;
767
+ samples.push(
768
+ item.raw.slice(Math.max(0, m.index - 10), m.index + m[0].length + 2).trim()
769
+ );
770
+ }
771
+ return { count, samples };
772
+ });
773
+ if (stackRes) tics.push(stackRes);
774
+
775
+ // 9. 过度精炼短段(反去 AI 味过火成电报体守卫)
776
+ if (
777
+ dCfg.overcompressedProseTic &&
778
+ !disabledRuleIds.has(dCfg.overcompressedProseTic.id)
779
+ ) {
780
+ const oc = dCfg.overcompressedProseTic;
781
+ let narChars = 0;
782
+ let narParas = 0;
783
+ let shortParas = 0;
784
+ let particles = 0;
785
+ let firstLine = null;
786
+ const samples = [];
787
+ for (const item of prepared) {
788
+ if (oc.panelLineRegex.test(item.raw.trim())) continue;
789
+ if (item.narrationLen === 0) continue;
790
+ if (firstLine === null) firstLine = item.line;
791
+ narParas += 1;
792
+ narChars += item.narrationLen;
793
+ if (item.narrationLen <= oc.shortMaxChars) {
794
+ shortParas += 1;
795
+ if (samples.length < 5) samples.push(item.narration.trim());
796
+ }
797
+ const pMatches = item.narration.match(oc.particleRegex);
798
+ if (pMatches) particles += pMatches.length;
799
+ }
800
+ const shortRatio = narParas > 0 ? shortParas / narParas : 0;
801
+ const particlePerKilo = narChars > 0 ? (particles / narChars) * 1000 : 0;
802
+ if (
803
+ narChars >= oc.minChars &&
804
+ narParas >= oc.minParas &&
805
+ shortRatio >= oc.shortRatio &&
806
+ particlePerKilo < oc.maxParticlePerKilo
807
+ ) {
808
+ tics.push({
809
+ id: oc.id,
810
+ layer: "universal",
811
+ category: oc.id,
812
+ line: firstLine,
813
+ hits: shortParas,
814
+ perKilo: Number(particlePerKilo.toFixed(1)),
815
+ samples,
816
+ level: "advisory",
817
+ review: oc.review || "semantic",
818
+ remedy: oc.remedy,
819
+ });
820
+ }
821
+ }
822
+
823
+ // 10. 低连接密度(白话虚词连接与中长承接句同时偏低)
824
+ if (
825
+ dCfg.lowConnectiveDensityTic &&
826
+ !disabledRuleIds.has(dCfg.lowConnectiveDensityTic.id)
827
+ ) {
828
+ const lc = dCfg.lowConnectiveDensityTic;
829
+ let bodyChars = 0;
830
+ let fnHits = 0;
831
+ let plHits = 0;
832
+ let firstLine = null;
833
+ const sentLens = [];
834
+ const samples = [];
835
+ for (const item of prepared) {
836
+ if (item.narrationLen === 0) continue;
837
+ if (firstLine === null) firstLine = item.line;
838
+ bodyChars += item.narrationLen;
839
+ fnHits += countLiteralTerms(item.narration, lc.functionTerms);
840
+ plHits += countLiteralTerms(item.narration, lc.plainTerms);
841
+ for (const s of splitCleanSentences(item.narration, sentenceSplit)) {
842
+ const len = countVisibleChars(s, visibleCharRegex);
843
+ if (len === 0) continue;
844
+ sentLens.push(len);
845
+ if (len <= 12 && samples.length < 5) samples.push(s);
846
+ }
847
+ }
848
+ const fnPerKilo = bodyChars > 0 ? (fnHits / bodyChars) * 1000 : 0;
849
+ const plPerKilo = bodyChars > 0 ? (plHits / bodyChars) * 1000 : 0;
850
+ const longRatio =
851
+ sentLens.length > 0
852
+ ? sentLens.filter((len) => len >= lc.longSentChars).length / sentLens.length
853
+ : 0;
854
+ if (
855
+ bodyChars >= lc.minChars &&
856
+ sentLens.length > 0 &&
857
+ fnPerKilo < lc.maxFunctionPerKilo &&
858
+ plPerKilo < lc.maxPlainPerKilo &&
859
+ longRatio < lc.maxLongSentRatio
860
+ ) {
861
+ tics.push({
862
+ id: lc.id,
863
+ layer: "universal",
864
+ category: lc.id,
865
+ line: firstLine,
866
+ hits: sentLens.length,
867
+ perKilo: Number(fnPerKilo.toFixed(1)),
868
+ samples,
869
+ level: "advisory",
870
+ review: lc.review || "semantic",
871
+ remedy: lc.remedy,
872
+ });
873
+ }
874
+ }
875
+
876
+ // 11. 连续无叙述动作锚点的纯对话流检测
877
+ if (
878
+ dCfg.dialogueOnlyStreakTic &&
879
+ !disabledRuleIds.has(dCfg.dialogueOnlyStreakTic.id)
880
+ ) {
881
+ const dc = dCfg.dialogueOnlyStreakTic;
882
+ let streak = 0;
883
+ let streakStartLine = null;
884
+ let maxStreak = 0;
885
+ let maxStartLine = null;
886
+ let curSamples = [];
887
+ let bestSamples = [];
888
+ for (const item of prepared) {
889
+ const trimmed = item.wlText.trim();
890
+ const isPureQuoteLine =
891
+ trimmed.length > 0 &&
892
+ item.narrationLen === 0 &&
893
+ dc.quoteLineRegex.test(trimmed);
894
+ if (isPureQuoteLine) {
895
+ if (streak === 0) {
896
+ streakStartLine = item.line;
897
+ curSamples = [];
898
+ }
899
+ streak += 1;
900
+ if (curSamples.length < 4) curSamples.push(item.raw.trim());
901
+ if (streak > maxStreak) {
902
+ maxStreak = streak;
903
+ maxStartLine = streakStartLine;
904
+ bestSamples = curSamples;
905
+ }
906
+ } else {
907
+ streak = 0;
908
+ streakStartLine = null;
909
+ curSamples = [];
910
+ }
911
+ }
912
+ if (maxStreak >= (dc.minStreak || 8)) {
913
+ tics.push({
914
+ id: dc.id,
915
+ layer: "universal",
916
+ category: dc.id,
917
+ line: maxStartLine,
918
+ hits: maxStreak,
919
+ samples: bestSamples,
920
+ level: "advisory",
921
+ review: dc.review || "semantic",
922
+ remedy: dc.remedy,
923
+ });
924
+ }
925
+ }
926
+
927
+ return tics;
928
+ }
929
+
930
+ // 剥离单行与跨行 HTML 注释为等长空格,防止隐藏标记误报(未闭合注释保留正文)
931
+ function stripHtmlCommentsFromLines(rawLines) {
932
+ const result = [];
933
+ let inComment = false;
934
+ const openFlags = rawLines.map((l) => l.includes("<!--"));
935
+ const closeFlags = rawLines.map((l) => l.includes("-->"));
936
+ let hasCloseAhead = new Array(rawLines.length + 1).fill(false);
937
+ for (let i = rawLines.length - 1; i >= 0; i -= 1) {
938
+ hasCloseAhead[i] = closeFlags[i] || hasCloseAhead[i + 1];
939
+ }
940
+
941
+ for (let idx = 0; idx < rawLines.length; idx += 1) {
942
+ let line = rawLines[idx];
943
+ let out = "";
944
+ let cursor = 0;
945
+ while (cursor < line.length) {
946
+ if (inComment) {
947
+ const close = line.indexOf("-->", cursor);
948
+ const end = close === -1 ? line.length : close + 3;
949
+ out += " ".repeat(end - cursor);
950
+ cursor = end;
951
+ if (close !== -1) inComment = false;
952
+ } else {
953
+ const start = line.indexOf("<!--", cursor);
954
+ if (start === -1) {
955
+ out += line.slice(cursor);
956
+ break;
957
+ }
958
+ out += line.slice(cursor, start) + " ";
959
+ cursor = start + 4;
960
+ const closesSameLine = line.indexOf("-->", cursor) !== -1;
961
+ if (closesSameLine || hasCloseAhead[idx + 1]) {
962
+ inComment = true;
963
+ }
964
+ }
965
+ }
966
+ if (!openFlags[idx] || out.trim().length > 0 || line.trim().length === 0) {
967
+ result.push({ line: idx + 1, text: out, trimmed: out.trim() });
968
+ }
969
+ }
970
+ return result;
971
+ }
972
+
973
+ // 跳过 YAML Frontmatter、HTML 注释、代码块围栏、标题与分隔线后的有效正文行
974
+ function extractScannableBodyLines(rawContent, dgCfg, lingConfig) {
975
+ const rawLines = String(rawContent || "").split(/\r?\n/u);
976
+ const cleaned = stripHtmlCommentsFromLines(rawLines);
977
+ const body = [];
978
+ let fenceChar = null;
979
+ let inFrontMatter =
980
+ cleaned.length > 1 &&
981
+ cleaned[0].trimmed === "---" &&
982
+ cleaned.slice(1, 30).some((l) => /^[A-Za-z0-9_-]+:\s*/u.test(l.trimmed));
983
+
984
+ const headingPrefix = lingConfig.tokens?.markdownHeadingPrefix || "#";
985
+ const markdownRule = lingConfig.tokens?.markdownRule || "---";
986
+ for (let i = 0; i < cleaned.length; i += 1) {
987
+ const item = cleaned[i];
988
+ if (inFrontMatter) {
989
+ if (i > 0 && item.trimmed === "---") inFrontMatter = false;
990
+ continue;
991
+ }
992
+ const fence = /^(`{3,}|~{3,})/u.exec(item.trimmed);
993
+ if (fenceChar) {
994
+ if (fence && item.trimmed[0] === fenceChar) fenceChar = null;
995
+ continue;
996
+ }
997
+ if (fence) {
998
+ fenceChar = item.trimmed[0];
999
+ continue;
1000
+ }
1001
+ if (!item.trimmed) continue;
1002
+ if (item.trimmed.startsWith(headingPrefix)) continue;
1003
+ if (item.trimmed === markdownRule) continue;
1004
+ if (dgCfg?.dividerRegex && dgCfg.dividerRegex.test(item.trimmed)) continue;
1005
+ body.push(item);
1006
+ }
1007
+ return body;
1008
+ }
1009
+
1010
+ // 提取用于语言学画像与规则扫描的含汉字正文自然段
1011
+ export function extractBodyParagraphLines(rawContent, customLingConfig) {
1012
+ const cfg = customLingConfig;
1013
+ if (!cfg) {
1014
+ throw new Error("linguisticsConfig is required for extractBodyParagraphLines.");
1015
+ }
1016
+ const dgCfg = cfg.compiledRegex?.degeneration || null;
1017
+ const hanRegex = cfg.compiledRegex.hanCharGlobal;
1018
+ const bodyLines = extractScannableBodyLines(rawContent, dgCfg, cfg);
1019
+ const paragraphs = [];
1020
+ for (const item of bodyLines) {
1021
+ const matches = item.trimmed.match(hanRegex);
1022
+ const hanLen = matches ? matches.length : 0;
1023
+ if (hanLen > 0) {
1024
+ paragraphs.push({
1025
+ line: item.line,
1026
+ text: item.trimmed,
1027
+ hanLen,
1028
+ });
1029
+ }
1030
+ }
1031
+ return paragraphs;
1032
+ }
1033
+
1034
+ // 运行模型退化与工程词泄漏检测(复读、截断、AI 自指/占位符、Tier1/Tier2 工程词)
1035
+ export function runDegenerationChecks(
1036
+ rawContent,
1037
+ lingConfig,
1038
+ whitelistLiterals = [],
1039
+ disabledRuleIds = new Set()
1040
+ ) {
1041
+ const dg = lingConfig.compiledRegex.degeneration;
1042
+ if (!dg) return { degenerationHits: [], metaLeakHits: [] };
1043
+
1044
+ const quoteRegexes = lingConfig.compiledRegex.quoteMaskRegexes || [];
1045
+ const visibleCharRegex = lingConfig.compiledRegex.visibleCharGlobal;
1046
+ const wlMaskChar = lingConfig.tokens.whitelistMaskChar || " ";
1047
+ const body = extractScannableBodyLines(rawContent, dg, lingConfig);
1048
+
1049
+ const degenerationHits = [];
1050
+ const metaLeakHits = [];
1051
+
1052
+ const prepared = body.map((item) => {
1053
+ const wlText = maskWhitelistLiterals(
1054
+ item.text,
1055
+ whitelistLiterals,
1056
+ wlMaskChar
1057
+ );
1058
+ const narration = maskQuotedText(wlText, quoteRegexes, " ");
1059
+ return {
1060
+ line: item.line,
1061
+ raw: item.trimmed,
1062
+ wlText: wlText.trim(),
1063
+ narration: narration.trim(),
1064
+ };
1065
+ });
1066
+
1067
+ // 1. 紧邻整行复读(排除纯对话刷屏)
1068
+ if (!disabledRuleIds.has("degen_adjacent_repeat")) {
1069
+ for (let i = 1; i < prepared.length; i += 1) {
1070
+ if (
1071
+ prepared[i].wlText === prepared[i - 1].wlText &&
1072
+ countVisibleChars(prepared[i].narration, visibleCharRegex) >=
1073
+ dg.adjacentRepeatMinLen
1074
+ ) {
1075
+ degenerationHits.push({
1076
+ id: "degen_adjacent_repeat",
1077
+ layer: "universal",
1078
+ category: "verbatim_repeat",
1079
+ line: prepared[i].line,
1080
+ matched: prepared[i].raw.slice(0, 40),
1081
+ level: "blocking",
1082
+ review: "mechanical",
1083
+ });
1084
+ }
1085
+ }
1086
+ }
1087
+
1088
+ // 2. 全章长句复读(引号外叙述长句出现 >=3 次)
1089
+ if (!disabledRuleIds.has("degen_sentence_repeat")) {
1090
+ const sentCounts = new Map();
1091
+ for (const item of prepared) {
1092
+ for (const s of splitCleanSentences(item.narration, dg.sentenceSplitRegex)) {
1093
+ if (countVisibleChars(s, visibleCharRegex) < dg.sentenceRepeatMinLen) continue;
1094
+ sentCounts.set(s, (sentCounts.get(s) || 0) + 1);
1095
+ }
1096
+ }
1097
+ const flagged = new Set();
1098
+ for (const [s, cnt] of sentCounts) {
1099
+ if (cnt >= dg.sentenceRepeatMinCount) flagged.add(s);
1100
+ }
1101
+ if (flagged.size > 0) {
1102
+ for (const item of prepared) {
1103
+ for (const s of splitCleanSentences(item.narration, dg.sentenceSplitRegex)) {
1104
+ if (flagged.has(s)) {
1105
+ degenerationHits.push({
1106
+ id: "degen_sentence_repeat",
1107
+ layer: "universal",
1108
+ category: "verbatim_repeat",
1109
+ line: item.line,
1110
+ matched: `${s.slice(0, 36)} (x${sentCounts.get(s)})`,
1111
+ level: "blocking",
1112
+ review: "mechanical",
1113
+ });
1114
+ flagged.delete(s);
1115
+ }
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ // 3. 章末截断检测(剥除尾部 Markdown 强调符后检查终止标点)
1122
+ if (!disabledRuleIds.has("degen_truncated_ending") && prepared.length > 0) {
1123
+ const contentOnly = prepared.filter(
1124
+ (item) =>
1125
+ !dg.chapterHeadingRegex.test(item.raw) &&
1126
+ !dg.endSignoffRegex.test(item.raw)
1127
+ );
1128
+ if (contentOnly.length > 0) {
1129
+ const last = contentOnly[contentOnly.length - 1];
1130
+ const normalizedTail = last.raw.replace(dg.trailingMarkdownStripRegex, "");
1131
+ if (normalizedTail && !dg.terminalPunctuationRegex.test(normalizedTail)) {
1132
+ degenerationHits.push({
1133
+ id: "degen_truncated_ending",
1134
+ layer: "universal",
1135
+ category: "truncated_ending",
1136
+ line: last.line,
1137
+ matched: last.raw.slice(-32),
1138
+ level: "blocking",
1139
+ review: "mechanical",
1140
+ });
1141
+ }
1142
+ }
1143
+ }
1144
+
1145
+ // 4. 占位符 / 乱码 / AI 自指与拒绝语
1146
+ for (const item of prepared) {
1147
+ for (const pRule of dg.placeholderRules || []) {
1148
+ if (disabledRuleIds.has(pRule.id)) continue;
1149
+ const target = pRule.scope === "narration" ? item.narration : item.wlText;
1150
+ pRule.regex.lastIndex = 0;
1151
+ const m = pRule.regex.exec(target);
1152
+ if (m) {
1153
+ degenerationHits.push({
1154
+ id: pRule.id,
1155
+ layer: "universal",
1156
+ category: "placeholder_or_refusal",
1157
+ line: item.line,
1158
+ matched: m[0],
1159
+ level: "blocking",
1160
+ review: "mechanical",
1161
+ remedy: pRule.remedy,
1162
+ });
1163
+ }
1164
+ }
1165
+ }
1166
+
1167
+ // 5. 写作工程词泄漏(Tier 1 必改阻塞;Tier 2 引号外叙述提示)
1168
+ for (const item of prepared) {
1169
+ if (dg.chapterHeadingRegex.test(item.raw) || dg.endSignoffRegex.test(item.raw)) {
1170
+ continue;
1171
+ }
1172
+ if (dg.metaLeakTier1Regex && !disabledRuleIds.has("meta_leak_tier1")) {
1173
+ dg.metaLeakTier1Regex.lastIndex = 0;
1174
+ let m;
1175
+ while ((m = dg.metaLeakTier1Regex.exec(item.wlText)) !== null) {
1176
+ metaLeakHits.push({
1177
+ id: "meta_leak_tier1",
1178
+ layer: "universal",
1179
+ category: "engineering_meta_leak",
1180
+ line: item.line,
1181
+ matched: m[0],
1182
+ level: "blocking",
1183
+ review: "mechanical",
1184
+ });
1185
+ }
1186
+ }
1187
+ if (dg.metaLeakTier2Regex && !disabledRuleIds.has("meta_leak_tier2")) {
1188
+ dg.metaLeakTier2Regex.lastIndex = 0;
1189
+ let m;
1190
+ while ((m = dg.metaLeakTier2Regex.exec(item.narration)) !== null) {
1191
+ metaLeakHits.push({
1192
+ id: "meta_leak_tier2",
1193
+ layer: "universal",
1194
+ category: "chapter_meta_reference",
1195
+ line: item.line,
1196
+ matched: m[0],
1197
+ level: "advisory",
1198
+ review: "semantic",
1199
+ });
1200
+ }
1201
+ }
1202
+ }
1203
+
1204
+ return { degenerationHits, metaLeakHits };
1205
+ }
1206
+
1207
+ // 从细纲文本中收集显式放行的原话与复沓锚句白名单
1208
+ function collectOutlineExemptPhrases(outlineText, lingConfig, extraExempt = []) {
1209
+ const exemptSet = new Set();
1210
+ for (const phrase of extraExempt || []) {
1211
+ if (typeof phrase === "string" && phrase.trim().length > 0) {
1212
+ exemptSet.add(phrase.trim());
1213
+ }
1214
+ }
1215
+
1216
+ const headerPattern = lingConfig.outlineCopy?.exemptHeaderRegex;
1217
+ const headerRe = headerPattern ? new RegExp(headerPattern) : null;
1218
+ const quoteRegexes = lingConfig.compiledRegex?.quoteMaskRegexes || [];
1219
+ const lines = String(outlineText || "").split(/\r?\n/);
1220
+
1221
+ for (const rawLine of lines) {
1222
+ const trimmed = rawLine.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "").trim();
1223
+ if (!trimmed || !headerRe) continue;
1224
+ const headerMatch = headerRe.exec(trimmed);
1225
+ if (!headerMatch) continue;
1226
+
1227
+ const rest = trimmed.slice(headerMatch[0].length).trim();
1228
+ if (!rest) continue;
1229
+
1230
+ let foundQuoted = false;
1231
+ for (const qRe of quoteRegexes) {
1232
+ qRe.lastIndex = 0;
1233
+ let m;
1234
+ while ((m = qRe.exec(rest)) !== null) {
1235
+ foundQuoted = true;
1236
+ const inner = m[0].slice(1, -1).trim();
1237
+ if (inner.length >= 2) exemptSet.add(inner);
1238
+ }
1239
+ }
1240
+
1241
+ if (!foundQuoted) {
1242
+ for (const part of rest.split(/[/|\uff5c\uff0c,\uff1b;]+/)) {
1243
+ const clean = part.trim();
1244
+ if (clean.length >= 4) exemptSet.add(clean);
1245
+ }
1246
+ }
1247
+ }
1248
+
1249
+ return Array.from(exemptSet);
1250
+ }
1251
+
1252
+ // 检测正文是否大段照搬章节细纲文字(支持白名单原话/复沓锚句豁免)
1253
+ export function checkOutlineCopy(chapterText, outlineText, options = {}) {
1254
+ const lingConfig = options.lingConfig;
1255
+ if (!lingConfig) {
1256
+ throw new Error("lingConfig is required for checkOutlineCopy.");
1257
+ }
1258
+ const minRun = Math.max(
1259
+ 4,
1260
+ Number(options.minRun ?? lingConfig.outlineCopy?.minRunChars ?? 16)
1261
+ );
1262
+
1263
+ if (!chapterText || !outlineText) {
1264
+ return { pass: true, minRun, overlapCount: 0, hits: [] };
1265
+ }
1266
+
1267
+ const exemptPhrases = collectOutlineExemptPhrases(
1268
+ outlineText,
1269
+ lingConfig,
1270
+ options.exemptPhrases
1271
+ );
1272
+ const headerPattern = lingConfig.outlineCopy?.exemptHeaderRegex;
1273
+ const headerRe = headerPattern ? new RegExp(headerPattern) : null;
1274
+ const rawHeading = lingConfig.compiledRegex?.degeneration?.chapterHeadingRegex;
1275
+ const chHeadingRe = rawHeading instanceof RegExp ? rawHeading : null;
1276
+
1277
+ // 提取细纲正文片段并建立定长滑动窗口索引
1278
+ const gramMap = new Map();
1279
+ const outlineLines = String(outlineText).split(/\r?\n/);
1280
+ for (let i = 0; i < outlineLines.length; i += 1) {
1281
+ const lineNo = i + 1;
1282
+ const rawLine = outlineLines[i].trim();
1283
+ if (!rawLine || /^\s*#{1,6}\s/.test(rawLine)) continue;
1284
+
1285
+ const noBullet = rawLine.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "").trim();
1286
+ if (headerRe && headerRe.test(noBullet)) continue;
1287
+
1288
+ const cleanedPrefix = noBullet.replace(/^\[[^\]]+\]\s*[:\uff1a]?\s*/, "");
1289
+ const masked = maskWhitelistLiterals(
1290
+ cleanedPrefix,
1291
+ exemptPhrases,
1292
+ "\u0000"
1293
+ ).replace(/[*_]/g, "");
1294
+
1295
+ for (const part of masked.split(/[\u0000:\uff1a\r\n]+/)) {
1296
+ const compact = part.replace(/\s+/g, "");
1297
+ if (compact.length < minRun) continue;
1298
+ for (let pos = 0; pos <= compact.length - minRun; pos += 1) {
1299
+ const gram = compact.slice(pos, pos + minRun);
1300
+ if (!gramMap.has(gram)) {
1301
+ gramMap.set(gram, { outlineLine: lineNo, fragment: compact, pos });
1302
+ }
1303
+ }
1304
+ }
1305
+ }
1306
+
1307
+ if (gramMap.size === 0) {
1308
+ return { pass: true, minRun, overlapCount: 0, hits: [] };
1309
+ }
1310
+
1311
+ // 逐行扫描正文,合并同段连续命中的抄纲片段
1312
+ const hits = [];
1313
+ const chapterLines = String(chapterText).split(/\r?\n/);
1314
+ for (let i = 0; i < chapterLines.length; i += 1) {
1315
+ const lineNo = i + 1;
1316
+ const rawLine = chapterLines[i].trim();
1317
+ if (!rawLine) continue;
1318
+ if (chHeadingRe) {
1319
+ chHeadingRe.lastIndex = 0;
1320
+ if (chHeadingRe.test(rawLine)) continue;
1321
+ }
1322
+
1323
+ const masked = maskWhitelistLiterals(rawLine, exemptPhrases, "\u0000").replace(
1324
+ /[*_]/g,
1325
+ ""
1326
+ );
1327
+
1328
+ for (const part of masked.split("\u0000")) {
1329
+ const compact = part.replace(/\s+/g, "");
1330
+ if (compact.length < minRun) continue;
1331
+
1332
+ let pos = 0;
1333
+ while (pos <= compact.length - minRun) {
1334
+ const gram = compact.slice(pos, pos + minRun);
1335
+ const matchInfo = gramMap.get(gram);
1336
+ if (!matchInfo) {
1337
+ pos += 1;
1338
+ continue;
1339
+ }
1340
+
1341
+ // 向后尽量延伸重叠区间,避免同一句拆分多条重复报警
1342
+ let ext = minRun;
1343
+ while (
1344
+ pos + ext < compact.length &&
1345
+ matchInfo.pos + ext < matchInfo.fragment.length &&
1346
+ compact[pos + ext] === matchInfo.fragment[matchInfo.pos + ext]
1347
+ ) {
1348
+ ext += 1;
1349
+ }
1350
+
1351
+ const matched = compact.slice(pos, pos + ext);
1352
+ hits.push({
1353
+ line: lineNo,
1354
+ outlineLine: matchInfo.outlineLine,
1355
+ matched,
1356
+ length: matched.length,
1357
+ });
1358
+ pos += ext;
1359
+ }
1360
+ }
1361
+ }
1362
+
1363
+ return {
1364
+ pass: hits.length === 0,
1365
+ minRun,
1366
+ overlapCount: hits.length,
1367
+ hits,
1368
+ };
1369
+ }
1370
+
1371
+ // 解析中文数字或阿拉伯数字为整数(零中文字符字面量,映射表来自 JSON 配置)
1372
+ export function parseChineseOrArabicNumber(token, chineseNumerals = {}) {
1373
+ if (!token) return null;
1374
+ const trimmed = String(token).trim();
1375
+ if (/^\d+$/.test(trimmed)) {
1376
+ return Number(trimmed);
1377
+ }
1378
+
1379
+ const digits = chineseNumerals.digits || {};
1380
+ const units = chineseNumerals.units || {};
1381
+ let total = 0;
1382
+ let current = 0;
1383
+ let hasDigit = false;
1384
+ let seenValid = false;
1385
+
1386
+ for (const ch of trimmed) {
1387
+ if (Object.prototype.hasOwnProperty.call(digits, ch)) {
1388
+ current = digits[ch];
1389
+ hasDigit = true;
1390
+ seenValid = true;
1391
+ } else if (Object.prototype.hasOwnProperty.call(units, ch)) {
1392
+ const unit = units[ch];
1393
+ // 处理“十 / 十二”开头省略“一”的情况
1394
+ if (!hasDigit && current === 0 && unit === 10) {
1395
+ current = 1;
1396
+ }
1397
+ total += current * unit;
1398
+ current = 0;
1399
+ hasDigit = false;
1400
+ seenValid = true;
1401
+ }
1402
+ }
1403
+
1404
+ total += current;
1405
+ return seenValid ? total : null;
1406
+ }
1407
+
1408
+ // 校验引号相邻句的“短短 X 字 / 这 X 个字”字数宣称是否与引号内实际字数一致
1409
+ export function checkCharCountClaims(
1410
+ rawContent,
1411
+ customLingConfig,
1412
+ whitelistLiterals = []
1413
+ ) {
1414
+ if (!rawContent) return [];
1415
+ const cfg = customLingConfig;
1416
+ if (!cfg) {
1417
+ throw new Error("linguisticsConfig is required for checkCharCountClaims.");
1418
+ }
1419
+ const claimCfg = cfg.charCountClaim || {};
1420
+ const cn = cfg.chineseNumerals || {};
1421
+ const hanGlobal = cfg.compiledRegex?.hanCharGlobal;
1422
+ const visGlobal = cfg.compiledRegex?.visibleCharGlobal || hanGlobal;
1423
+ const wlMaskChar = cfg.tokens?.whitelistMaskChar || " ";
1424
+
1425
+ const postRe = claimCfg.postQuoteRegex
1426
+ ? new RegExp(claimCfg.postQuoteRegex, "gu")
1427
+ : null;
1428
+ const preRe = claimCfg.preQuoteRegex
1429
+ ? new RegExp(claimCfg.preQuoteRegex, "gu")
1430
+ : null;
1431
+
1432
+ if (!postRe && !preRe) return [];
1433
+
1434
+ const countChars = (str, re) => {
1435
+ if (!str || !re) return 0;
1436
+ const m = str.match(re);
1437
+ return m ? m.length : 0;
1438
+ };
1439
+
1440
+ const hits = [];
1441
+ const lines = String(rawContent).split(/\r?\n/u);
1442
+
1443
+ lines.forEach((rawLine, idx) => {
1444
+ const lineNo = idx + 1;
1445
+ const maskedLine = maskWhitelistLiterals(
1446
+ rawLine,
1447
+ whitelistLiterals,
1448
+ wlMaskChar
1449
+ );
1450
+ const seenPositions = new Set();
1451
+
1452
+ const inspectMatch = (quote, claimToken, fullMatch, matchIndex) => {
1453
+ const dedupKey = `${lineNo}:${matchIndex}`;
1454
+ if (seenPositions.has(dedupKey)) return;
1455
+ if (!quote || quote.includes("\u2026") || quote.includes("...")) return;
1456
+
1457
+ const claimed = parseChineseOrArabicNumber(claimToken, cn);
1458
+ if (claimed === null || claimed < 1 || claimed > 20) return;
1459
+
1460
+ const hanCount = countChars(quote, hanGlobal);
1461
+ const visCount = countChars(quote, visGlobal);
1462
+ if (claimed !== hanCount && claimed !== visCount) {
1463
+ seenPositions.add(dedupKey);
1464
+ hits.push({
1465
+ line: lineNo,
1466
+ matched: fullMatch,
1467
+ quote,
1468
+ claimed,
1469
+ actual: hanCount,
1470
+ });
1471
+ }
1472
+ };
1473
+
1474
+ if (postRe) {
1475
+ postRe.lastIndex = 0;
1476
+ let m;
1477
+ while ((m = postRe.exec(maskedLine)) !== null) {
1478
+ inspectMatch(m[1], m[2], m[0], m.index);
1479
+ }
1480
+ }
1481
+
1482
+ if (preRe) {
1483
+ preRe.lastIndex = 0;
1484
+ let m;
1485
+ while ((m = preRe.exec(maskedLine)) !== null) {
1486
+ inspectMatch(m[2], m[1], m[0], m.index);
1487
+ }
1488
+ }
1489
+ });
1490
+
1491
+ return hits;
1492
+ }
1493
+
1494
+ // 校验章节细纲是否缺失核心情节要素或残留未填占位符
1495
+ export function checkOutlineContract(outlineText, options = {}) {
1496
+ const cfg = options.lingConfig;
1497
+ if (!cfg) {
1498
+ throw new Error("lingConfig is required for checkOutlineContract.");
1499
+ }
1500
+ const contract = cfg.outlineContract || {};
1501
+ const placeholderRe = contract.placeholderRegex
1502
+ ? new RegExp(contract.placeholderRegex, "giu")
1503
+ : null;
1504
+
1505
+ const placeholderHits = [];
1506
+ const lines = String(outlineText || "").split(/\r?\n/u);
1507
+ if (placeholderRe) {
1508
+ lines.forEach((line, idx) => {
1509
+ placeholderRe.lastIndex = 0;
1510
+ let m;
1511
+ while ((m = placeholderRe.exec(line)) !== null) {
1512
+ placeholderHits.push({
1513
+ line: idx + 1,
1514
+ matched: m[0].trim(),
1515
+ });
1516
+ if (m[0].length === 0) placeholderRe.lastIndex += 1;
1517
+ }
1518
+ });
1519
+ }
1520
+
1521
+ const missingFacets = [];
1522
+ for (const facet of contract.requiredFacets || []) {
1523
+ if (!facet || !facet.pattern) continue;
1524
+ const facetRe = new RegExp(facet.pattern, "iu");
1525
+ if (!facetRe.test(String(outlineText || ""))) {
1526
+ missingFacets.push(facet.id);
1527
+ }
1528
+ }
1529
+
1530
+ return {
1531
+ pass: missingFacets.length === 0 && placeholderHits.length === 0,
1532
+ missingFacets,
1533
+ placeholderCount: placeholderHits.length,
1534
+ placeholderHits,
1535
+ };
1536
+ }