dislop 0.7.1 → 0.8.1

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 (45) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +4 -3
  4. package/.cursor-plugin/plugin.json +3 -2
  5. package/PRODUCT.md +18 -4
  6. package/README.md +72 -38
  7. package/README.zh-CN.md +70 -40
  8. package/bin/dislop.mjs +2883 -309
  9. package/gemini-extension.json +2 -2
  10. package/package.json +19 -3
  11. package/packs/business-brief/pack.json +336 -6
  12. package/packs/core/pack.json +14 -7
  13. package/packs/deck-and-ui/pack.json +255 -6
  14. package/packs/literary-essay/pack.json +20 -0
  15. package/patterns/ai-tic-rubric.json +252 -0
  16. package/patterns/banks/composite-fusion.json +13 -1
  17. package/patterns/banks/lexical-signals.json +20 -2
  18. package/patterns/banks/syntactic-frames.json +10 -3
  19. package/patterns/banks/visual-deck.json +7 -0
  20. package/patterns/dimensions/discourse.json +26 -0
  21. package/patterns/dimensions/lexical.json +26 -0
  22. package/patterns/dimensions/rhythm.json +52 -0
  23. package/patterns/dimensions/visual-and-deck.json +209 -1
  24. package/plugin.json +4 -3
  25. package/server.json +2 -2
  26. package/skills/dislop/SKILL.md +35 -41
  27. package/skills/dislop/agents/openai.yaml +1 -1
  28. package/skills/dislop/references/essay.md +24 -0
  29. package/skills/dislop/references/essay.zh-CN.md +24 -0
  30. package/skills/dislop/references/office.md +23 -0
  31. package/skills/dislop/references/office.zh-CN.md +23 -0
  32. package/skills/dislop/references/web-ui.md +24 -0
  33. package/skills/dislop/references/web-ui.zh-CN.md +24 -0
  34. package/skills/dislop/references/work-docs.md +25 -0
  35. package/skills/dislop/references/work-docs.zh-CN.md +24 -0
  36. package/src/binary-node.mjs +1716 -1
  37. package/src/core.mjs +3215 -247
  38. package/src/local-model.mjs +31 -11
  39. package/src/pattern-engine.mjs +174 -24
  40. package/src/pocket-model.mjs +27 -5
  41. package/src/review-client.mjs +1064 -0
  42. package/skills/dislop/references/business-and-rfc.md +0 -26
  43. package/skills/dislop/references/editorial-and-essay.md +0 -20
  44. package/skills/dislop/references/regulated-and-precision.md +0 -27
  45. package/skills/dislop/references/web-ui-and-deck.md +0 -26
package/src/core.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  * Shared identically by Node CLI, Node MCP server, and Browser Workbench (`site/`).
4
4
  */
5
5
 
6
- export const ENGINE_VERSION = "0.7.1";
6
+ export const ENGINE_VERSION = "0.8.1";
7
7
 
8
8
  export const SEVERITY_RANK = {
9
9
  info: 1,
@@ -12,6 +12,338 @@ export const SEVERITY_RANK = {
12
12
  never: 99,
13
13
  };
14
14
 
15
+ export const VALID_REGISTERS = Object.freeze([
16
+ "unspecified",
17
+ "official",
18
+ "casual",
19
+ "argumentative",
20
+ "technical",
21
+ "marketing",
22
+ "narrative",
23
+ ]);
24
+
25
+ const VALID_REGISTER_SET = new Set(VALID_REGISTERS);
26
+
27
+ function expandBraces(pattern) {
28
+ const m = String(pattern || "").match(/\{([^{}]+)\}/);
29
+ if (!m) return [String(pattern || "")];
30
+ const prefix = pattern.slice(0, m.index);
31
+ const suffix = pattern.slice(m.index + m[0].length);
32
+ return m[1].split(",").flatMap((part) => expandBraces(prefix + part.trim() + suffix));
33
+ }
34
+
35
+ function globToRegExp(glob) {
36
+ const norm = String(glob || "").replace(/\\/g, "/").replace(/^\.\//, "");
37
+ let rx = "^";
38
+ for (let i = 0; i < norm.length; i += 1) {
39
+ const ch = norm[i];
40
+ if (ch === "*" && norm[i + 1] === "*") {
41
+ if (norm[i + 2] === "/") {
42
+ rx += "(?:.+/)?";
43
+ i += 2;
44
+ } else {
45
+ rx += ".*";
46
+ i += 1;
47
+ }
48
+ } else if (ch === "*") {
49
+ rx += "[^/]*";
50
+ } else if (ch === "?") {
51
+ rx += "[^/]";
52
+ } else if ("+.^$|()[]{}".includes(ch)) {
53
+ rx += "\\" + ch;
54
+ } else {
55
+ rx += ch;
56
+ }
57
+ }
58
+ rx += "$";
59
+ return new RegExp(rx);
60
+ }
61
+
62
+ export function matchesAnyGlob(relPosix, globs = []) {
63
+ const clean = String(relPosix || "").replace(/\\/g, "/").replace(/^\.\//, "");
64
+ return (globs || []).flatMap(expandBraces).some((g) => globToRegExp(g).test(clean));
65
+ }
66
+
67
+ export function validateConfig(config) {
68
+ if (config === null || config === undefined) return config;
69
+ if (typeof config !== "object" || Array.isArray(config)) {
70
+ throw new Error("Invalid config: expected JSON object");
71
+ }
72
+ if (config.failOn !== undefined && config.failOn !== null) {
73
+ if (typeof config.failOn !== "string" || !SEVERITY_RANK[config.failOn]) {
74
+ throw new Error("Invalid config 'failOn': expected error, warning, info, or never");
75
+ }
76
+ }
77
+ if (config.register !== undefined && config.register !== null) {
78
+ if (typeof config.register !== "string") {
79
+ throw new Error("Invalid config 'register': expected string");
80
+ }
81
+ const norm = config.register.trim().toLowerCase();
82
+ if (norm !== "" && !VALID_REGISTER_SET.has(norm)) {
83
+ throw new Error(`Invalid config register '${config.register}' (expected ${VALID_REGISTERS.join(", ")})`);
84
+ }
85
+ }
86
+ if (config.overrides !== undefined && config.overrides !== null) {
87
+ if (!Array.isArray(config.overrides)) {
88
+ throw new Error("Invalid config 'overrides': expected array");
89
+ }
90
+ for (const ov of config.overrides) {
91
+ if (!ov || typeof ov !== "object" || Array.isArray(ov)) {
92
+ throw new Error("Invalid config 'overrides' item: expected object");
93
+ }
94
+ if (ov.register !== undefined && ov.register !== null) {
95
+ if (typeof ov.register !== "string") {
96
+ throw new Error("Invalid config override 'register': expected string");
97
+ }
98
+ const ovNorm = ov.register.trim().toLowerCase();
99
+ if (ovNorm !== "" && !VALID_REGISTER_SET.has(ovNorm)) {
100
+ throw new Error(`Invalid config override register '${ov.register}' (expected ${VALID_REGISTERS.join(", ")})`);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ return config;
106
+ }
107
+
108
+ export function parseFrontMatterRegister(text) {
109
+ if (typeof text !== "string" || text.length === 0) return null;
110
+ const stripped = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
111
+ const fm = stripped.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/);
112
+ if (!fm) return null;
113
+ let genericReg = null;
114
+ const lines = fm[1].split(/\r?\n/);
115
+ for (const rawLine of lines) {
116
+ // Only top-level unindented YAML keys (skips nested mappings and indented block scalars)
117
+ const m = rawLine.match(/^(dislop_register|register):[ \t]*(.*?)[ \t]*(?:#.*)?$/);
118
+ if (!m) continue;
119
+ const key = m[1].toLowerCase();
120
+ let rawVal = (m[2] || "").trim();
121
+ if (
122
+ (rawVal.startsWith('"') && rawVal.endsWith('"') && rawVal.length >= 2) ||
123
+ (rawVal.startsWith("'") && rawVal.endsWith("'") && rawVal.length >= 2)
124
+ ) {
125
+ rawVal = rawVal.slice(1, -1).trim();
126
+ }
127
+ const val = rawVal.toLowerCase();
128
+ if (key === "dislop_register") {
129
+ if (!val || !VALID_REGISTER_SET.has(val)) {
130
+ throw new Error(
131
+ `Invalid dislop_register '${rawVal}' in frontmatter (expected ${VALID_REGISTERS.join(", ")})`
132
+ );
133
+ }
134
+ return val;
135
+ }
136
+ if (genericReg === null && VALID_REGISTER_SET.has(val)) {
137
+ genericReg = val;
138
+ }
139
+ }
140
+ return genericReg;
141
+ }
142
+
143
+ export function resolveRegister(text = "", { filename = "<memory>", flagRegister = null, config = {} } = {}) {
144
+ validateConfig(config);
145
+ if (flagRegister !== null && flagRegister !== undefined) {
146
+ if (typeof flagRegister !== "string") {
147
+ throw new Error(`Invalid --register (expected string: auto, ${VALID_REGISTERS.join(", ")})`);
148
+ }
149
+ if (flagRegister.trim() !== "") {
150
+ const norm = flagRegister.trim().toLowerCase();
151
+ if (norm !== "auto") {
152
+ if (!VALID_REGISTER_SET.has(norm)) {
153
+ throw new Error(`Invalid --register '${flagRegister}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
154
+ }
155
+ return { register: norm, registerSource: "flag" };
156
+ }
157
+ }
158
+ }
159
+
160
+ const mod = detectModality(filename);
161
+ if (mod === null || mod === "markdown" || mod === "text") {
162
+ const fmReg = parseFrontMatterRegister(text);
163
+ if (fmReg) {
164
+ return { register: fmReg, registerSource: "frontmatter" };
165
+ }
166
+ }
167
+
168
+ const rel = String(filename || "").replace(/\\/g, "/").replace(/^\.\//, "");
169
+ for (const ov of config?.overrides || []) {
170
+ if (!ov || !ov.register) continue;
171
+ const ovReg = ov.register.trim().toLowerCase();
172
+ if (!ovReg) continue;
173
+ const patterns = Array.isArray(ov.files) ? ov.files : ov.files ? [ov.files] : [];
174
+ if (patterns.length > 0 && matchesAnyGlob(rel, patterns)) {
175
+ return { register: ovReg, registerSource: "config" };
176
+ }
177
+ }
178
+
179
+ if (config?.register && config.register.trim() !== "") {
180
+ return { register: config.register.trim().toLowerCase(), registerSource: "config" };
181
+ }
182
+
183
+ return { register: "unspecified", registerSource: "default" };
184
+ }
185
+
186
+ export function applyRegisterOverride(rule, register = "unspecified", config = {}) {
187
+ if (!register || register === "unspecified" || rule.tier === "invariant") {
188
+ return { skip: false, rule, registerAdjusted: false };
189
+ }
190
+ const userRuleOverride = config?.rules?.[rule.id];
191
+ if (typeof userRuleOverride === "string" && SEVERITY_RANK[userRuleOverride]) {
192
+ return { skip: false, rule, registerAdjusted: false };
193
+ }
194
+ const ov = rule.registerOverrides?.[register];
195
+ if (!ov) {
196
+ return { skip: false, rule, registerAdjusted: false };
197
+ }
198
+ if (ov.action === "skip") {
199
+ return { skip: true, rule: null, registerAdjusted: true };
200
+ }
201
+ const effective = {
202
+ ...rule,
203
+ ...(ov.severity && SEVERITY_RANK[ov.severity] ? { severity: ov.severity } : {}),
204
+ ...(ov.message ? { message: ov.message } : {}),
205
+ ...(ov.deletionTest ? { deletionTest: ov.deletionTest } : {}),
206
+ ...(ov.revisionKind ? { revisionKind: ov.revisionKind } : {}),
207
+ ...(ov.revisionScope ? { revisionScope: ov.revisionScope } : {}),
208
+ ...(ov.revisionAvoid ? { revisionAvoid: ov.revisionAvoid } : {}),
209
+ };
210
+ return { skip: false, rule: effective, registerAdjusted: true };
211
+ }
212
+
213
+ export const SCENARIO_STRATEGIES = Object.freeze({
214
+ technical: {
215
+ id: "technical",
216
+ label: { en: "Engineering Spec & RFC", zh: "研发文档与复盘" },
217
+ cut: {
218
+ en: "Remove marketing hype, code-diff parroting, hollow 'not human error' excuses, and ownerless action items.",
219
+ zh: "删掉营销形容词、纯复述 Diff 的句子、“并非单纯人为失误”套话和无责任人的待办项。",
220
+ },
221
+ protect: {
222
+ en: "Keep uniform constraint lists, semicolon preconditions, CLI/code identifiers, exact thresholds, and parameter tables intact.",
223
+ zh: "保留等长的约束条款、分号并列前置条件、代码/命令标识、阈值数字与参数表,不强求文学长短句起伏。",
224
+ },
225
+ avoid: {
226
+ en: "Do not alter code identifiers, weaken numeric bounds, or add casual chatter.",
227
+ zh: "绝不改写代码标识、放宽数值边界,也不要为了所谓人味掺入随口聊天腔。",
228
+ },
229
+ },
230
+ official: {
231
+ id: "official",
232
+ label: { en: "Official & Regulated Notice", zh: "公文、合规与正式通告" },
233
+ cut: {
234
+ en: "Strip unsubstantiated superlatives, unanchored multipliers, AI chat greetings, and empty slogans lacking a referent.",
235
+ zh: "删掉无证据绝对化承诺、悬空倍数、AI 寒暄壳,以及没有具体指代的空洞口号。",
236
+ },
237
+ protect: {
238
+ en: "Preserve formal institutional phrasing, numbered clauses, legal disclaimers, and scope qualifiers ('only if', 'unless').",
239
+ zh: "保留规范书面措辞、条款编号、责任边界、法律免责与限定条件(如“仅限”“除非”)。",
240
+ },
241
+ avoid: {
242
+ en: "Do not rewrite formal clauses into casual slang or invent unverified compliance guarantees.",
243
+ zh: "不要把正式条款改成轻浮口语,也绝不补写未核实的合规承诺。",
244
+ },
245
+ },
246
+ argumentative: {
247
+ id: "argumentative",
248
+ label: { en: "Business Brief & Essay-Argument", zh: "工作简报与观点长文" },
249
+ cut: {
250
+ en: "Cut macro-trend openers, buzzword clusters, 3-part balanced semicolon pitches, 'Not X, but Y' slogans, and unsourced claims.",
251
+ zh: "切掉宏观趋势开场、热词共现、三段对称分号推销句、“不是 A 而是 B”金句和无出处背书。",
252
+ },
253
+ protect: {
254
+ en: "Keep upfront conclusions, concrete metrics, genuine trade-off contrasts, and named internal data sources.",
255
+ zh: "保留前置结论与关键数字、带真实动作的取舍对比,以及具名后台/实测数据来源。",
256
+ },
257
+ avoid: {
258
+ en: "Do not trade one slogan for another aphorism or add macro sign-offs ('Looking ahead').",
259
+ zh: "不要把一种套话换成另一句金句,更别在结尾补写“展望未来”式拔高。",
260
+ },
261
+ },
262
+ narrative: {
263
+ id: "narrative",
264
+ label: { en: "Literary Essay & Column", zh: "随笔、专栏与叙事非虚构" },
265
+ cut: {
266
+ en: "Strip moralizing endings, stock AI metaphors, stiff translationese, mechanical Q&A transitions, and halfwidth CJK punctuation.",
267
+ zh: "删掉结尾强行升华、陈旧 AI 意象、生硬欧化翻译腔、机械设问过渡与中文里的半角标点。",
268
+ },
269
+ protect: {
270
+ en: "Preserve sensory details, dialogue, author rhythm contrast, deliberate short dramatic beats, and natural flowing sentences.",
271
+ zh: "保留现场细节、人物原话、个人节奏起伏、有意的短句停顿和通顺的流水长句。",
272
+ },
273
+ avoid: {
274
+ en: "Do not flatten personal prose into technical bullet points or invent scenes missing from the notes.",
275
+ zh: "不要把个人叙述改呆板成工程条目,也绝不外编素材里没有的细节。",
276
+ },
277
+ },
278
+ casual: {
279
+ id: "casual",
280
+ label: { en: "Conversational & Personal Post", zh: "口语帖、闲置转卖与社区分享" },
281
+ cut: {
282
+ en: "Remove scripted influencer clichés, customer-service filler wrappers, chatbot openings, and injected corporate jargon.",
283
+ zh: "去掉网红脚本腔、刻意客服套话、AI 开场白和硬塞进去的企业黑话。",
284
+ },
285
+ protect: {
286
+ en: "Preserve first-person spoken phrasing, conversational cadence, and recurring shop or shipping policy lines verbatim.",
287
+ zh: "保留第一人称口语词、日常停顿节奏,以及固定交易/发货规则短句。",
288
+ },
289
+ avoid: {
290
+ en: "Do not inflate spoken wording into stiff bookish prose or cycle synonyms on recurring policy lines.",
291
+ zh: "绝不为了规避重复把口语改成生硬书面腔(如把“自己收的”改成“仅出/略有/旨在”),也无需同义词轮换。",
292
+ },
293
+ },
294
+ marketing: {
295
+ id: "marketing",
296
+ label: { en: "Product & Launch Copy", zh: "产品介绍与发布文案" },
297
+ cut: {
298
+ en: "Remove generic AI SaaS hype ('unleash', 'supercharge', 'new era'), empty triads, and unverified speed/quality claims.",
299
+ zh: "删掉千篇一律的 AI 营销大词(赋能/颠覆/新纪元)、空洞三段排比和无基准夸大宣称。",
300
+ },
301
+ protect: {
302
+ en: "Keep concrete product mechanisms, intentional punchy benefit lines, and verified user counts or benchmarks.",
303
+ zh: "保留具体产品机制、有实质信息的短促利益点,以及实测或真实用户数字。",
304
+ },
305
+ avoid: {
306
+ en: "Do not invent customer metrics or pad short benefits into abstract manifesto paragraphs.",
307
+ zh: "不编造用户数据,不把短促清楚的功能点抻成长段虚词。",
308
+ },
309
+ },
310
+ "deck-ui": {
311
+ id: "deck-ui",
312
+ label: { en: "Slides, PDF & Web UI", zh: "PPT、海报与网页界面" },
313
+ cut: {
314
+ en: "Cut vague topic slide titles, >120-word slide walls, dead '#' links, purple-pink gradients, pill soup, and nested boxes.",
315
+ zh: "去掉空泛主题式标题、整屏文字墙、空 '#' 链接、紫粉霓虹渐变、胶囊标签墙和多层套盒。",
316
+ },
317
+ protect: {
318
+ en: "Keep action-takeaway titles, concise UI slot copy, real interactive routes, and single-screen hierarchy.",
319
+ zh: "保留直接说结论的标题、简短清晰的界面词条、真实跳转路径与单屏层级结构。",
320
+ },
321
+ avoid: {
322
+ en: "Never expand microcopy past its container slot or add decorative 'AI-Powered' badges.",
323
+ zh: "界面短文案改写长度不得超过原位置容量,不加装饰性 AI 标签。",
324
+ },
325
+ },
326
+ });
327
+
328
+ const PACK_DEFAULT_STRATEGY = Object.freeze({
329
+ "engineering-spec": "technical",
330
+ "regulated-comms": "official",
331
+ "literary-essay": "narrative",
332
+ "deck-and-ui": "deck-ui",
333
+ "executive-deck": "deck-ui",
334
+ "business-brief": "argumentative",
335
+ core: "argumentative",
336
+ });
337
+
338
+ export function getScenarioStrategy({ packId = "business-brief", register = "unspecified" } = {}) {
339
+ const regNorm = String(register || "").trim().toLowerCase();
340
+ if (regNorm && regNorm !== "unspecified" && regNorm !== "auto" && SCENARIO_STRATEGIES[regNorm]) {
341
+ return SCENARIO_STRATEGIES[regNorm];
342
+ }
343
+ const key = PACK_DEFAULT_STRATEGY[packId] || "argumentative";
344
+ return SCENARIO_STRATEGIES[key] || SCENARIO_STRATEGIES.argumentative;
345
+ }
346
+
15
347
  const EXT_TO_MODALITY = {
16
348
  ".md": "markdown",
17
349
  ".mdx": "markdown",
@@ -24,6 +356,12 @@ const EXT_TO_MODALITY = {
24
356
  ".svg": "svg",
25
357
  ".docx": "docx",
26
358
  ".pptx": "pptx",
359
+ ".pdf": "pdf",
360
+ ".png": "image",
361
+ ".jpg": "image",
362
+ ".jpeg": "image",
363
+ ".webp": "image",
364
+ ".gif": "image",
27
365
  };
28
366
 
29
367
  export function detectModality(filename = "") {
@@ -35,12 +373,90 @@ export function detectModality(filename = "") {
35
373
  }
36
374
 
37
375
  export function defaultPackForModality(modality) {
38
- if (modality === "html" || modality === "css" || modality === "jsx" || modality === "svg" || modality === "pptx") {
376
+ if (
377
+ modality === "html" ||
378
+ modality === "css" ||
379
+ modality === "jsx" ||
380
+ modality === "svg" ||
381
+ modality === "pptx" ||
382
+ modality === "pdf" ||
383
+ modality === "image"
384
+ ) {
39
385
  return "deck-and-ui";
40
386
  }
41
387
  return "business-brief";
42
388
  }
43
389
 
390
+ export function codePointLength(str) {
391
+ let count = 0;
392
+ const s = String(str || "");
393
+ for (let i = 0; i < s.length; i += 1) {
394
+ const c = s.charCodeAt(i);
395
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
396
+ const c2 = s.charCodeAt(i + 1);
397
+ if (c2 >= 0xdc00 && c2 <= 0xdfff) i += 1;
398
+ }
399
+ count += 1;
400
+ }
401
+ return count;
402
+ }
403
+
404
+ export function sliceCodepoints(str, maxCp) {
405
+ const s = String(str || "");
406
+ if (maxCp <= 0) return "";
407
+ let count = 0;
408
+ let i = 0;
409
+ while (i < s.length && count < maxCp) {
410
+ const c = s.charCodeAt(i);
411
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
412
+ const c2 = s.charCodeAt(i + 1);
413
+ if (c2 >= 0xdc00 && c2 <= 0xdfff) i += 2;
414
+ else i += 1;
415
+ } else {
416
+ i += 1;
417
+ }
418
+ count += 1;
419
+ }
420
+ return s.slice(0, i);
421
+ }
422
+
423
+ export function isLongFormHtmlDocument(rawHtml) {
424
+ const raw = String(rawHtml || "");
425
+ if (!raw.trim()) return false;
426
+ if (/(?:class\s*=\s*["'][^"']*\b(?:reveal|slides)\b|data-slide\b)/i.test(raw)) return false;
427
+ const slideCls = raw.match(/class\s*=\s*["'][^"']*\bslide\b/gi) || [];
428
+ if (slideCls.length >= 2) return false;
429
+ const zones = buildZones(raw, "html");
430
+ const visible = zones.proseLogical ?? zones.prose;
431
+ const cjkChars = (visible.match(/[\u4e00-\u9fff]/gu) || []).length;
432
+ const enWords = visible.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
433
+ if (cjkChars >= 600 || enWords >= 250) return true;
434
+ const blocks = visible.split(/\n+| {5,}/).map((b) => b.trim()).filter(Boolean);
435
+ let substantialBlocks = 0;
436
+ for (const blk of blocks) {
437
+ const blkCjk = (blk.match(/[\u4e00-\u9fff]/gu) || []).length;
438
+ const blkEn = blk.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
439
+ if (blkCjk >= 20 || blkEn >= 14) substantialBlocks += 1;
440
+ if (substantialBlocks >= 2) return true;
441
+ }
442
+ return false;
443
+ }
444
+
445
+ export function hasEmbeddedUiMarkup(rawMarkdown) {
446
+ let s = maskMarkdownFences(String(rawMarkdown || ""), new Set());
447
+ s = s.replace(/`[^`\n]+`/g, " ");
448
+ const uiTags = s.match(/<(?:(?:div|section|article|header|nav|button)\b[^>]*(?:class(?:Name)?=|style=)|a\b[^>]*(?:class(?:Name)?=|style=|href=["'](?:#|javascript:|\s*["']))|svg\b[^>]*>)/gi) || [];
449
+ return uiTags.length >= 2;
450
+ }
451
+
452
+ export function computeRulesetHash(pack) {
453
+ const parts = (pack?.rules || [])
454
+ .map((r) => `${r.id}:${r.severity || "warning"}`)
455
+ .sort()
456
+ .join("|");
457
+ return fnv1aHex(`${ENGINE_VERSION}|${pack?.id || ""}|${parts}`);
458
+ }
459
+
44
460
  export function resolveEffectivePack(packId, packsById, config = {}) {
45
461
  const target = packsById[packId];
46
462
  if (!target) {
@@ -173,31 +589,103 @@ function buildCodePointPrefix(text) {
173
589
  return prefix;
174
590
  }
175
591
 
176
- function isSentenceBreakAt(text, idx) {
592
+ export function isSentenceBreakAt(text, idx) {
177
593
  const ch = text[idx];
178
594
  if (!ch || !/[\n.!?。!?]/.test(ch)) return false;
179
595
  if (ch !== ".") return true;
180
596
  const prev = idx > 0 ? text[idx - 1] : "";
181
597
  const next = idx + 1 < text.length ? text[idx + 1] : "";
182
- if (/\d/.test(prev) && /\d/.test(next)) return false;
598
+ if (/[0-9]/.test(prev) && /[0-9]/.test(next)) return false;
599
+ if (/[A-Za-z0-9_-]/.test(prev) && /[a-z0-9]/.test(next)) return false;
183
600
  const beforeWord = text.slice(Math.max(0, idx - 6), idx);
184
601
  if (/(?:^|\s)(?:vs|v|approx|e\.g|i\.e)$/i.test(beforeWord)) return false;
185
602
  return true;
186
603
  }
187
604
 
188
- function enclosingSentence(text, start, end) {
605
+ function buildSentenceBreakIndices(text) {
606
+ const breaks = [];
607
+ for (let i = 0; i < text.length; i += 1) {
608
+ const ch = text[i];
609
+ if (ch === "\n" || ch === "." || ch === "!" || ch === "?" || ch === "。" || ch === "!" || ch === "?") {
610
+ if (isSentenceBreakAt(text, i)) breaks.push(i);
611
+ }
612
+ }
613
+ return breaks;
614
+ }
615
+
616
+ function enclosingSentence(text, start, end, breakIndices = null) {
617
+ let left = 0;
618
+ let right = text.length;
619
+ if (Array.isArray(breakIndices) && breakIndices.length > 0) {
620
+ // Upper bound for last break strictly before `start`
621
+ let lo = 0;
622
+ let hi = breakIndices.length - 1;
623
+ let prevBreak = -1;
624
+ while (lo <= hi) {
625
+ const mid = (lo + hi) >> 1;
626
+ if (breakIndices[mid] < start) {
627
+ prevBreak = breakIndices[mid];
628
+ lo = mid + 1;
629
+ } else {
630
+ hi = mid - 1;
631
+ }
632
+ }
633
+ if (prevBreak !== -1) left = prevBreak + 1;
634
+
635
+ // Lower bound for first break >= end
636
+ lo = 0;
637
+ hi = breakIndices.length - 1;
638
+ let nextBreak = -1;
639
+ while (lo <= hi) {
640
+ const mid = (lo + hi) >> 1;
641
+ if (breakIndices[mid] >= end) {
642
+ nextBreak = breakIndices[mid];
643
+ hi = mid - 1;
644
+ } else {
645
+ lo = mid + 1;
646
+ }
647
+ }
648
+ if (nextBreak !== -1) right = nextBreak;
649
+ } else {
650
+ left = start;
651
+ while (left > 0 && !isSentenceBreakAt(text, left - 1)) {
652
+ left -= 1;
653
+ }
654
+ right = end;
655
+ while (right < text.length && !isSentenceBreakAt(text, right)) {
656
+ right += 1;
657
+ }
658
+ }
659
+ if (right < text.length && /[.!?。!?]/.test(text[right])) {
660
+ right += 1;
661
+ }
662
+ return sliceCodepoints(text.slice(left, right).trim(), 240);
663
+ }
664
+
665
+ function enclosingSentenceUnclipped(text, start, end) {
666
+ const lineStart = Math.max(0, text.lastIndexOf("\n", Math.max(0, start - 1)) + 1);
667
+ let lineEnd = text.indexOf("\n", end);
668
+ if (lineEnd === -1) lineEnd = text.length;
669
+ const lineText = text.slice(lineStart, lineEnd);
670
+ const codeRanges = [];
671
+ const codeRe = /`[^`\n]+`/g;
672
+ let cm;
673
+ while ((cm = codeRe.exec(lineText)) !== null) {
674
+ codeRanges.push([lineStart + cm.index, lineStart + cm.index + cm[0].length]);
675
+ }
676
+ const inBackticks = (idx) => codeRanges.some(([s, e]) => idx >= s && idx < e);
189
677
  let left = start;
190
- while (left > 0 && !isSentenceBreakAt(text, left - 1)) {
678
+ while (left > lineStart && (inBackticks(left - 1) || !isSentenceBreakAt(text, left - 1))) {
191
679
  left -= 1;
192
680
  }
193
681
  let right = end;
194
- while (right < text.length && !isSentenceBreakAt(text, right)) {
682
+ while (right < lineEnd && (inBackticks(right) || !isSentenceBreakAt(text, right))) {
195
683
  right += 1;
196
684
  }
197
- if (right < text.length && /[.!?。!?]/.test(text[right])) {
685
+ if (right < lineEnd && !inBackticks(right) && /[.!?。!?]/.test(text[right])) {
198
686
  right += 1;
199
687
  }
200
- return text.slice(left, right).trim().slice(0, 240);
688
+ return text.slice(left, right).trim();
201
689
  }
202
690
 
203
691
  /**
@@ -246,11 +734,138 @@ export function parseSuppressions(text) {
246
734
  return { byTargetLine, directives };
247
735
  }
248
736
 
737
+ const HTML_ENTITY_NAMED = {
738
+ lt: "<",
739
+ gt: ">",
740
+ amp: "&",
741
+ quot: '"',
742
+ apos: "'",
743
+ nbsp: " ",
744
+ mdash: "—",
745
+ ndash: "–",
746
+ hellip: "…",
747
+ };
748
+
749
+ const HTML_ENTITY_RE = /&(?:#([0-9]+)|#x([0-9a-fA-F]+)|lt|gt|amp|quot|apos|nbsp|mdash|ndash|hellip);/gi;
750
+
751
+ function decodeEntityToken(m, dec, hex) {
752
+ if (dec) {
753
+ const cp = Number(dec);
754
+ return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : " ";
755
+ }
756
+ if (hex) {
757
+ const cp = parseInt(hex, 16);
758
+ return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : " ";
759
+ }
760
+ return HTML_ENTITY_NAMED[m.slice(1, -1).toLowerCase()] || null;
761
+ }
762
+
763
+ function decodeHtmlEntitiesPreservingLength(str) {
764
+ return String(str).replace(HTML_ENTITY_RE, (m, dec, hex) => {
765
+ const ch = decodeEntityToken(m, dec, hex);
766
+ if (!ch) return m;
767
+ if (ch.length <= m.length) return ch + " ".repeat(m.length - ch.length);
768
+ return sliceCodepoints(ch, 1) + " ".repeat(Math.max(0, m.length - sliceCodepoints(ch, 1).length));
769
+ });
770
+ }
771
+
772
+ function decodeHtmlWithOffsetMap(str) {
773
+ const s = String(str || "");
774
+ if (!s.includes("&")) return null;
775
+ let out = "";
776
+ const mapStarts = [];
777
+ const mapEnds = [];
778
+ let last = 0;
779
+ let matchedAny = false;
780
+ HTML_ENTITY_RE.lastIndex = 0;
781
+ let m;
782
+ while ((m = HTML_ENTITY_RE.exec(s)) !== null) {
783
+ for (let k = last; k < m.index; k += 1) {
784
+ out += s[k];
785
+ mapStarts.push(k);
786
+ mapEnds.push(k + 1);
787
+ }
788
+ const ch = decodeEntityToken(m[0], m[1], m[2]);
789
+ if (ch !== null) {
790
+ matchedAny = true;
791
+ for (let u = 0; u < ch.length; u += 1) {
792
+ out += ch[u];
793
+ mapStarts.push(m.index);
794
+ mapEnds.push(m.index + m[0].length);
795
+ }
796
+ } else {
797
+ for (let k = m.index; k < m.index + m[0].length; k += 1) {
798
+ out += s[k];
799
+ mapStarts.push(k);
800
+ mapEnds.push(k + 1);
801
+ }
802
+ }
803
+ last = m.index + m[0].length;
804
+ }
805
+ if (!matchedAny) return null;
806
+ for (let k = last; k < s.length; k += 1) {
807
+ out += s[k];
808
+ mapStarts.push(k);
809
+ mapEnds.push(k + 1);
810
+ }
811
+ return { text: out, mapStarts, mapEnds };
812
+ }
813
+
814
+ function maskMarkdownFences(text, proseFenceSet) {
815
+ const lines = text.split("\n");
816
+ const out = [];
817
+ let fenceChar = null;
818
+ let fenceLen = 0;
819
+ let keepBody = false;
820
+
821
+ for (let i = 0; i < lines.length; i += 1) {
822
+ const rawLine = lines[i];
823
+ const noCr = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
824
+ const cr = rawLine.endsWith("\r") ? "\r" : "";
825
+ const trimmed = noCr.trim();
826
+
827
+ if (!fenceChar) {
828
+ const m = noCr.match(/^[ \t]*(`{3,}|~{3,})(.*)$/);
829
+ if (m) {
830
+ fenceChar = m[1][0];
831
+ fenceLen = m[1].length;
832
+ const lang = m[2].trim().split(/\s+/)[0].toLowerCase();
833
+ keepBody = proseFenceSet.size > 0 && proseFenceSet.has(lang);
834
+ out.push(" ".repeat(noCr.length) + cr);
835
+ continue;
836
+ }
837
+ out.push(rawLine);
838
+ } else {
839
+ const closeRe = new RegExp(`^[ \\t]*${fenceChar}{${fenceLen},}[ \\t]*$`);
840
+ if (closeRe.test(trimmed)) {
841
+ fenceChar = null;
842
+ fenceLen = 0;
843
+ keepBody = false;
844
+ out.push(" ".repeat(noCr.length) + cr);
845
+ } else if (keepBody) {
846
+ out.push(rawLine);
847
+ } else {
848
+ out.push(" ".repeat(noCr.length) + cr);
849
+ }
850
+ }
851
+ }
852
+ return out.join("\n");
853
+ }
854
+
855
+ const HTML_BLOCK_BREAK_TAG_RE = /^<\/(?:p|div|li|td|th|tr|h[1-6]|section|article|header|footer|aside|blockquote|dt|dd|button|title)\b|^<br\b/i;
856
+
249
857
  /**
250
858
  * Build length-preserving masked views so character offsets match raw text 1:1.
251
859
  */
252
- export function buildZones(rawText, modality) {
860
+ export function buildZones(rawText, modality, options = {}) {
253
861
  const normText = String(rawText || "").replace(/\uFEFF/g, " ");
862
+ const proseFenceSet = new Set(
863
+ Array.isArray(options?.proseFences)
864
+ ? options.proseFences.map((s) => String(s || "").trim().toLowerCase()).filter(Boolean)
865
+ : []
866
+ );
867
+ const maskBlockquotes = options?.maskBlockquotes !== false;
868
+
254
869
  // Raw zone masks only inline dislop-ignore comment directives themselves
255
870
  const raw = normText
256
871
  .replace(/<!--\s*dislop-[\s\S]*?-->/gi, preserveLinesBlank)
@@ -271,35 +886,49 @@ export function buildZones(rawText, modality) {
271
886
  if (modality === "markdown" || modality === "text") {
272
887
  // YAML frontmatter
273
888
  prose = prose.replace(/^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?=\r?\n|$)/, preserveLinesBlank);
274
- // Fenced code blocks (closed pairs first, then any unclosed trailing fence)
275
- prose = prose.replace(/```[\s\S]*?```/g, preserveLinesBlank);
276
- prose = prose.replace(/~~~[\s\S]*?~~~/g, preserveLinesBlank);
277
- prose = prose.replace(/^[ \t]*```[\s\S]*$/m, preserveLinesBlank);
278
- prose = prose.replace(/^[ \t]*~~~[\s\S]*$/m, preserveLinesBlank);
889
+ // Fenced code blocks (supports optional proseFences allowlist)
890
+ prose = maskMarkdownFences(prose, proseFenceSet);
279
891
  // Inline code spans & strikethrough
280
892
  prose = prose.replace(/`[^`\n]+`/g, preserveLinesBlank);
281
893
  prose = prose.replace(/~~[^~\n]+~~/g, preserveLinesBlank);
282
894
  // Blockquotes (quoted external material)
283
- prose = prose.replace(/^[ \t]*>.*$/gm, preserveLinesBlank);
284
- // Markdown link targets ](url) while keeping visible [label]
285
- prose = prose.replace(/\]\([^)\n]+\)/g, (m) => "]" + preserveLinesBlank(m.slice(1)));
286
- } else if (modality === "html" || modality === "jsx" || modality === "svg") {
287
- // Strip tags in prose zone while preserving inner text offsets
288
- prose = prose.replace(/<[^>]+>/g, preserveLinesBlank);
895
+ if (maskBlockquotes) {
896
+ prose = prose.replace(/^[ \t]*>.*$/gm, preserveLinesBlank);
897
+ } else {
898
+ prose = prose.replace(/^[ \t]*(?:>[ \t]?)+/gm, preserveLinesBlank);
899
+ }
900
+ // Markdown link targets ](url) while keeping visible [label] and opening `(` for link lookahead
901
+ prose = prose.replace(/\]\([^)\n]+\)/g, (m) => "](" + preserveLinesBlank(m.slice(2)));
902
+ }
903
+ let proseLogical = null;
904
+ let proseMap = null;
905
+ if (modality === "html" || modality === "jsx" || modality === "svg") {
906
+ // Strip tags in prose zone while preserving offsets and inserting newlines at block boundaries
907
+ prose = prose.replace(/<[^>]+>/g, (tag) => {
908
+ if (HTML_BLOCK_BREAK_TAG_RE.test(tag) && tag.length >= 1) {
909
+ return preserveLinesBlank(tag.slice(0, -1)) + "\n";
910
+ }
911
+ return preserveLinesBlank(tag);
912
+ });
913
+ const decoded = decodeHtmlWithOffsetMap(prose);
914
+ if (decoded) {
915
+ proseLogical = decoded.text.replace(/https?:\/\/[^\s)>"'`]+/g, (u) => " ".repeat(u.length));
916
+ proseMap = { starts: decoded.mapStarts, ends: decoded.mapEnds };
917
+ }
918
+ prose = decodeHtmlEntitiesPreservingLength(prose);
289
919
  }
290
920
  // Mask bare URLs in prose
291
921
  prose = prose.replace(/https?:\/\/[^\s)>"'`]+/g, preserveLinesBlank);
292
922
 
293
923
  if (modality === "html" || modality === "jsx" || modality === "svg") {
294
- uiText = uiText.replace(/<[^>]+>/g, (tag) => {
295
- return preserveLinesBlank(tag);
296
- });
924
+ uiText = uiText.replace(/<[^>]+>/g, (tag) => preserveLinesBlank(tag));
925
+ uiText = decodeHtmlEntitiesPreservingLength(uiText);
297
926
  }
298
927
 
299
- return { raw, prose, "ui-text": uiText };
928
+ return { raw, prose, proseLogical, proseMap, "ui-text": uiText };
300
929
  }
301
930
 
302
- function isAllowedMatch(matchText, allowList = []) {
931
+ export function isAllowedMatch(matchText, allowList = []) {
303
932
  if (!allowList || allowList.length === 0) return false;
304
933
  const lower = matchText.toLowerCase();
305
934
  return allowList.some((item) => lower.includes(String(item).toLowerCase()));
@@ -309,22 +938,40 @@ function isAllowedMatch(matchText, allowList = []) {
309
938
 
310
939
  function probeNegationPivot(proseText, rawText) {
311
940
  const hits = [];
312
- // Chinese: 这不是/这绝非/并非只是/不仅仅是 A,而是/更是 B / 与其说 A,不如说 B
313
- const zhRegex = /(?:(?:这|那|它)?(?:(?:并)?不(?:是|只是|仅仅?是)|绝非|并非(?:只是)?)|与其说是?)([^,。!?;\n]{1,22})[,,;—]+\s*(?:而是|更是|不如说是?)([^。!?;\n]{1,28})/gu;
314
- const zhRhetoricalHead = /^(?:(?:这|那|它)|绝非|并非|与其|并?不(?:只是|仅仅?是))/;
941
+ const checkConcreteZh = (clauseA, clauseB, rawSlice) =>
942
+ (/\d/.test(clauseA) && /\d/.test(clauseB)) ||
943
+ /`/.test(rawSlice) ||
944
+ /\.[a-z]{2,4}\b/i.test(rawSlice) ||
945
+ /(?:第一次|第二次|站台|号楼|排第|星期|周[一二三四五六日天])/.test(rawSlice);
946
+
947
+ // Chinese 3-part: (这/那/它)(既)不是 A,也不是 B,而是/更是 C
948
+ const zhTripleRegex = /(?:(?:这|那|它)?(?:既)?(?:并)?不(?:是|只是|仅仅?是)|绝非|并非(?:只是)?)([^,。!?;\n]{1,22})[,,;—]+\s*也(?:并)?不(?:是|只是|仅仅?是)([^,。!?;\n]{1,22})[,,;—]+\s*(?:而是|更是)([^。!?;\n]{1,28})/gu;
949
+ // Chinese 2-part: 不是/绝非/并非/与其说/不仅(让/使/能/可以/在于/停留在)/不在(于)/不(搞/做/靠) A,而是/更是/不如说/而是在(于) B
950
+ const zhRegex = /(?:(?:这|那|它)?(?:(?:并)?不(?:是|只是|仅仅?是|仅(?:让|使|能|可以|在于|停留在)|在(?:于)?|搞|做|靠)|绝非|并非(?:只是)?)|与其说是?)([^,。!?;\n]{1,22})[,,;—]+\s*(?:而(?:是在(?:于)?|是|靠)|更(?:是|能|在于|让|使)|不如说是?)([^。!?;\n]{1,28})/gu;
951
+ const zhRhetoricalHead = /^(?:(?:这|那|它)|绝非|并非|与其|并?不(?:只是|仅仅?是|仅(?:让|使|能|可以|在于|停留在)|在(?:于)?|搞|做|靠))/;
315
952
  const zhFactualRootCause = /(?:报错|故障|原因|超时|磁盘|内存|耗尽|端口|进程|导致|因为|[A-Za-z_][A-Za-z0-9_-]{2,})/;
953
+ const coveredSpans = [];
954
+
316
955
  let m;
956
+ while ((m = zhTripleRegex.exec(proseText)) !== null) {
957
+ const clauseA = (m[1] || "").trim();
958
+ const clauseB = (m[2] || "").trim();
959
+ const clauseC = (m[3] || "").trim();
960
+ const rawSlice = rawText.slice(m.index, m.index + m[0].length);
961
+ if (checkConcreteZh(clauseA + clauseB, clauseC, rawSlice) || clauseC.length > 26 || !clauseA || !clauseB || !clauseC) {
962
+ continue;
963
+ }
964
+ coveredSpans.push([m.index, m.index + m[0].length]);
965
+ hits.push({ index: m.index, length: m[0].length });
966
+ }
967
+
317
968
  while ((m = zhRegex.exec(proseText)) !== null) {
969
+ if (coveredSpans.some(([s, e]) => m.index >= s && m.index < e)) continue;
318
970
  const clauseA = (m[1] || "").trim();
319
971
  const clauseB = (m[2] || "").trim();
320
972
  const rawSlice = rawText.slice(m.index, m.index + m[0].length);
321
973
  const contextBefore = rawText.slice(Math.max(0, m.index - 12), m.index);
322
- const bothHaveConcrete =
323
- (/\d/.test(clauseA) && /\d/.test(clauseB)) ||
324
- /`/.test(rawSlice) ||
325
- /\.[a-z]{2,4}\b/i.test(rawSlice) ||
326
- /(?:第一次|第二次|站台|号楼|排第|星期|周[一二三四五六日天])/.test(rawSlice);
327
- if (bothHaveConcrete || clauseB.length > 26 || !clauseA || !clauseB) {
974
+ if (checkConcreteZh(clauseA, clauseB, rawSlice) || clauseB.length > 26 || !clauseA || !clauseB) {
328
975
  continue;
329
976
  }
330
977
  if (!zhRhetoricalHead.test(m[0]) && zhFactualRootCause.test(contextBefore + rawSlice)) {
@@ -359,38 +1006,49 @@ function probeStaccatoRun(proseText) {
359
1006
  // Skip headings, lists, tables
360
1007
  if (/^(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\|)/.test(trimmed)) continue;
361
1008
 
362
- // Collect sentences with offsets inside paragraph
363
- const sentRegex = /[^.!?。!?\n]+[.!?。!?]/gu;
1009
+ // Collect sentences with offsets inside paragraph using decimal/version-safe boundary checks
364
1010
  const sentences = [];
365
- let sm;
366
- while ((sm = sentRegex.exec(para)) !== null) {
367
- const s = sm[0].trim();
368
- if (!s) continue;
1011
+ let i = 0;
1012
+ const n = para.length;
1013
+ while (i < n) {
1014
+ while (i < n && /[\s\r\n]/.test(para[i])) i += 1;
1015
+ if (i >= n) break;
1016
+ const segStart = i;
1017
+ while (i < n && para[i] !== "\n" && !(isSentenceBreakAt(para, i) && para[i] !== "\n")) {
1018
+ i += 1;
1019
+ }
1020
+ if (i >= n || para[i] === "\n") {
1021
+ // Non-terminated line fragment breaks any staccato run
1022
+ sentences.push({ start: pm.index + segStart, end: pm.index + i, isShort: false });
1023
+ if (i < n && para[i] === "\n") i += 1;
1024
+ continue;
1025
+ }
1026
+ while (i < n && /[.!?。!?]/.test(para[i])) i += 1;
1027
+ const s = para.slice(segStart, i).trim();
369
1028
  const body = s.replace(/[.!?。!?]+$/u, "").trim();
370
- if (!body) continue;
371
- const cjkCount = (body.match(/[\u4e00-\u9fff]/gu) || []).length;
372
- const enWords = body.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
373
- const isShort =
374
- (cjkCount >= 2 && cjkCount <= 6 && enWords <= 1 && !/[,,::;;]/.test(body)) ||
375
- (cjkCount === 0 && enWords >= 2 && enWords <= 4 && !/[,:;]/.test(body));
376
- sentences.push({
377
- start: pm.index + sm.index + sm[0].indexOf(s),
378
- end: pm.index + sm.index + sm[0].indexOf(s) + s.length,
379
- isShort,
380
- });
1029
+ if (body) {
1030
+ const cjkCount = (body.match(/[\u4e00-\u9fff]/gu) || []).length;
1031
+ const enWords = body.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
1032
+ const isShort =
1033
+ (cjkCount >= 2 && cjkCount <= 6 && enWords <= 1 && !/[,,::;;]/.test(body)) ||
1034
+ (cjkCount === 0 && enWords >= 2 && enWords <= 4 && !/[,:;]/.test(body));
1035
+ const leadInSeg = para.slice(segStart, i).indexOf(s);
1036
+ const start = pm.index + segStart + Math.max(0, leadInSeg);
1037
+ sentences.push({ start, end: start + s.length, isShort });
1038
+ }
381
1039
  }
382
1040
 
383
1041
  let runStart = -1;
384
1042
  let runCount = 0;
385
- for (let i = 0; i <= sentences.length; i += 1) {
386
- const cur = sentences[i];
1043
+ for (let k = 0; k <= sentences.length; k += 1) {
1044
+ const cur = sentences[k];
387
1045
  if (cur && cur.isShort) {
388
- if (runCount === 0) runStart = i;
1046
+ if (runCount === 0) runStart = k;
389
1047
  runCount += 1;
390
1048
  } else {
391
1049
  if (runCount >= 3) {
392
1050
  const first = sentences[runStart];
393
- const last = sentences[i - 1];
1051
+ const last = sentences[k - 1];
394
1052
  hits.push({ index: first.start, length: last.end - first.start });
395
1053
  }
396
1054
  runCount = 0;
@@ -400,21 +1058,34 @@ function probeStaccatoRun(proseText) {
400
1058
  return hits;
401
1059
  }
402
1060
 
1061
+ const ZH_TRIAD_SLOGAN_ROOTS = /(?:高效|精准|全面|智能|可靠|协同|赋能|闭环|引领|抓手|稳健|灵活|深度|多元|生态|敏捷|极致|易用|统筹|兼顾|推进|提质|增效|创新|优质|卓越|无缝|安全|稳定|科学|规范|统一|便捷|智慧|领先|透明|可控|弹性|全方位|立体)/u;
1062
+
403
1063
  function probeZhFourCharTriad(proseText) {
404
1064
  const hits = [];
405
- const triadRegex = /(?:^|[,。!?;:、“‘(\s]|(?:实现|具备|坚持|保持|做到|形成|打造|追求|提供|确保|了|是|的|以|向|为))([\u4e00-\u9fff]{4})[、,,]\s*([\u4e00-\u9fff]{4})[、,,]\s*([\u4e00-\u9fff]{4})(?=$|[,。!?;:、”’)\s]|[的地等])/gu;
406
- const entitySuffix = /(?:大学|学院|学校|公司|集团|银行|医院|中心|委员|政府|部门|机场|车站|高速|铁路|[省市区县镇乡])$/u;
1065
+ const triadRegex = /(?:^|[,。!?;:、“‘(\s]|(?:实现|具备|坚持|保持|做到|形成|打造|追求|提供|确保|了|是|的|以|向|为))([\u4e00-\u9fff]{4})[、,,·・]\s*([\u4e00-\u9fff]{4})[、,,·・]\s*([\u4e00-\u9fff]{4})(?=$|[,。!?;:、”’)\s·・]|[的地等])/gu;
1066
+ const entitySuffix = /(?:大学|学院|学校|公司|集团|银行|医院|中心|委员|政府|部门|机场|车站|高速|铁路|[省市区县镇乡]|编号|日期|时间|记录|清单|台账|出处|明细|汇总|报表|状态|字段|开关|配置|步骤|检查|规则|目录|路径|文档|手册|模板|脚本|接口|模块|节点|日志|指标|参数|列表|表格|工作表|表|拓扑|矩阵|样例|资产|结果|组合|读取|创建|输入|输出|去重|占用|冲回)$/u;
407
1067
  const brokenSlice = /[的了在或与及把被]/u;
408
1068
  let m;
409
1069
  while ((m = triadRegex.exec(proseText)) !== null) {
410
1070
  const items = [m[1], m[2], m[3]];
411
1071
  if (items.some((w) => entitySuffix.test(w) || brokenSlice.test(w))) continue;
412
- const triadStr = `${m[1]}${proseText.slice(m.index).match(/[、,,]/)[0]}${m[2]}`;
413
1072
  const startOffset = m.index + m[0].indexOf(m[1]);
1073
+ const endOffset = m.index + m[0].length;
414
1074
  const prevChar = startOffset > 0 ? proseText[startOffset - 1] : "";
415
1075
  if (prevChar === "《") continue;
416
- void triadStr;
417
- hits.push({ index: startOffset, length: m.index + m[0].length - startOffset });
1076
+ const before = proseText.slice(Math.max(0, startOffset - 24), startOffset);
1077
+ const after = proseText.slice(endOffset, Math.min(proseText.length, endOffset + 24));
1078
+ // Exempt 4+ item enumerations
1079
+ if (/[\u4e00-\u9fff]{4}\s*[、,,·・]\s*$/.test(before) || /^\s*[、,,·・]\s*[\u4e00-\u9fff]{4}/.test(after)) {
1080
+ continue;
1081
+ }
1082
+ // Exempt explicit technical/field enumeration context
1083
+ if (/(?:包括|包含|涵盖|设有|分为|列出|涉及|字段为|表名为|包含如下)[::]?\s*$/.test(before) && /^\s*等/.test(after)) {
1084
+ continue;
1085
+ }
1086
+ const sloganMatches = items.filter((w) => ZH_TRIAD_SLOGAN_ROOTS.test(w)).length;
1087
+ if (sloganMatches < 2) continue;
1088
+ hits.push({ index: startOffset, length: endOffset - startOffset });
418
1089
  }
419
1090
  return hits;
420
1091
  }
@@ -424,6 +1095,19 @@ function probeUnsourcedAttribution(proseText, rawText) {
424
1095
  const attrRegex = /\b(?:[Ss]tudies|[Rr]esearch|[Ii]ndustry\s+research|[Ee]xperts|[Dd]ata)\s+(?:shows?|suggests?|indicates?|proves?)\b|(?:研究|数据|专家|业内人士|行业报告)(?:表明|显示|指出|认为)[,,]?/gu;
425
1096
  let m;
426
1097
  while ((m = attrRegex.exec(proseText)) !== null) {
1098
+ // Grounded internal operational data: e.g. "客服后台明细数据显示近7天平均响应时长为 98分12秒。"
1099
+ if (m[0].startsWith("数据")) {
1100
+ const preClause = proseText.slice(Math.max(0, m.index - 24), m.index);
1101
+ const afterSlice = rawText.slice(m.index, Math.min(rawText.length, m.index + 80));
1102
+ if (
1103
+ /(?:客服|监控|日志|后台|明细|台账|实测|压测|统计|灰度|线上|本地|内部|本次|本期|本轮|订单|系统|埋点|审计|抽样)[\u4e00-\u9fffA-Za-z0-9_-]{0,12}$/.test(
1104
+ preClause
1105
+ ) &&
1106
+ /\d/.test(afterSlice)
1107
+ ) {
1108
+ continue;
1109
+ }
1110
+ }
427
1111
  // Inspect enclosing + lookahead window in rawText for citation markers, links, years, or《report》
428
1112
  const winStart = Math.max(0, m.index - 30);
429
1113
  const winEnd = Math.min(rawText.length, m.index + 180);
@@ -444,15 +1128,16 @@ function probeUnsourcedAttribution(proseText, rawText) {
444
1128
 
445
1129
  function probeBoldLeadListWall(proseText, rawText, minRun = 4) {
446
1130
  const hits = [];
447
- const lines = rawText.split(/\r?\n/);
1131
+ const rawLines = rawText.split("\n");
448
1132
  let offset = 0;
449
1133
  let runStartOffset = 0;
450
1134
  let runEndOffset = 0;
451
1135
  let runCount = 0;
452
1136
 
453
- for (let i = 0; i <= lines.length; i += 1) {
454
- const line = i < lines.length ? lines[i] : "";
455
- const proseLine = i < lines.length ? proseText.slice(offset, offset + line.length) : "";
1137
+ for (let i = 0; i <= rawLines.length; i += 1) {
1138
+ const rawLine = i < rawLines.length ? rawLines[i] : "";
1139
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1140
+ const proseLine = i < rawLines.length ? proseText.slice(offset, offset + line.length) : "";
456
1141
  const isBullet =
457
1142
  proseLine.trim().length > 0 &&
458
1143
  /^\s*(?:[-*+]|\d+[.)])\s+\*\*([^*\n`]{2,36})\*\*\s*[::—-]/.test(line);
@@ -460,13 +1145,13 @@ function probeBoldLeadListWall(proseText, rawText, minRun = 4) {
460
1145
  if (runCount === 0) runStartOffset = offset + line.search(/\S/);
461
1146
  runCount += 1;
462
1147
  runEndOffset = offset + line.length;
463
- } else if (i === lines.length || line.trim() !== "") {
1148
+ } else if (i === rawLines.length || line.trim() !== "") {
464
1149
  if (runCount >= minRun) {
465
1150
  hits.push({ index: runStartOffset, length: runEndOffset - runStartOffset });
466
1151
  }
467
1152
  runCount = 0;
468
1153
  }
469
- offset += line.length + 1;
1154
+ offset += rawLine.length + 1;
470
1155
  }
471
1156
  return hits;
472
1157
  }
@@ -566,19 +1251,43 @@ function countTextUnits(s) {
566
1251
  return countTextUnitsTenths(s) / 10;
567
1252
  }
568
1253
 
1254
+ export function stripParentheticals(str) {
1255
+ const out = [];
1256
+ let depth = 0;
1257
+ for (let i = 0; i < str.length; i += 1) {
1258
+ const ch = str[i];
1259
+ if (ch === "(" || ch === "(") {
1260
+ depth += 1;
1261
+ out.push(" ");
1262
+ } else if ((ch === ")" || ch === ")") && depth > 0) {
1263
+ depth -= 1;
1264
+ out.push(" ");
1265
+ } else if (depth > 0 && ch !== "\n" && ch !== "\r") {
1266
+ out.push(" ");
1267
+ } else {
1268
+ out.push(ch);
1269
+ }
1270
+ }
1271
+ return out.join("");
1272
+ }
1273
+
569
1274
  function countConcretenessAnchors(rawSlice) {
570
1275
  // Strip HTML comments before counting concrete anchors
571
1276
  const s = String(rawSlice || "").replace(/<!--[\s\S]*?-->/g, " ");
572
1277
  let count = 0;
573
1278
  count += (s.match(/(?<![A-Za-z0-9_])\d+(?:[.,:]\d+)?%?(?![A-Za-z0-9_])/g) || []).length;
1279
+ count += (s.match(/(?<![A-Za-z0-9_])[A-Z]{1,4}-?\d{1,3}(?![A-Za-z0-9_])/g) || []).length;
574
1280
  count += (s.match(/`[^`\n]+`/g) || []).length;
575
1281
  count += (s.match(/[/\\][A-Za-z0-9._-]+\.[a-z]{1,5}(?![A-Za-z0-9_])/gi) || []).length;
576
1282
  count += (s.match(/(?<![A-Za-z0-9_])(?:PR\s*#?\d+|v\d+\.\d+|HTTP\s*\d{3}|UTC|Q[1-4])(?![A-Za-z0-9_])/g) || []).length;
577
1283
  count += (
578
1284
  s.match(
579
- /(?:[一二三四五六七八九十两百千万]+[天月年次个张条座块斤米秒分时]|周[一二三四五六日天]|昨天|昨晚|今早|上周|下周|去年|前年|清晨|傍晚|凌晨|午后|十月|十一月|十二月)/gu
1285
+ /(?:[一二三四五六七八九十两百千万]+[天月年次个张条座块斤米秒分时人颗枚格炉瓶对]|周[一二三四五六日天]|昨天|昨晚|今早|上周|下周|去年|前年|清晨|傍晚|凌晨|午后|十月|十一月|十二月)/gu
580
1286
  ) || []
581
1287
  ).length;
1288
+ count += (s.match(/《[^》\n]{1,32}》/gu) || []).length;
1289
+ count += (s.match(/[「『“"][\u4e00-\u9fffA-Za-z0-9_/-]{1,16}[」』”"]/gu) || []).length;
1290
+ count += (s.match(/(?:点击|打开|勾选|切换|输入|选择|保存|导出|上传|下载|复制|粘贴|刷新|重启|执行|登录|填写|核对)/gu) || []).length;
582
1291
  return count;
583
1292
  }
584
1293
 
@@ -586,6 +1295,70 @@ function isStructuredLine(trimmedLine) {
586
1295
  return /^(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\||>)/.test(trimmedLine);
587
1296
  }
588
1297
 
1298
+ /**
1299
+ * Extract substantive Markdown list items and explanatory table cells with exact source offsets.
1300
+ */
1301
+ function extractStructuredProseBlocks(proseText, rawText) {
1302
+ const items = [];
1303
+ let pos = 0;
1304
+ const n = proseText.length;
1305
+ while (pos <= n) {
1306
+ const nl = proseText.indexOf("\n", pos);
1307
+ const lineEnd = nl === -1 ? n : nl;
1308
+ const lineProse = proseText.slice(pos, lineEnd);
1309
+ const lineRaw = rawText.slice(pos, lineEnd);
1310
+ const listMatch = lineProse.match(/^(\s*(?:[-*+]|\d+[.)])\s+)(.+)$/);
1311
+ if (listMatch) {
1312
+ const bodyStart = pos + listMatch[1].length;
1313
+ const bodyText = listMatch[2];
1314
+ const trimmed = bodyText.trim();
1315
+ const cjk = (trimmed.match(/[\u4e00-\u9fff]/gu) || []).length;
1316
+ const en = trimmed.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
1317
+ if (cjk >= 24 || en >= 15) {
1318
+ items.push({
1319
+ start: bodyStart + Math.max(0, bodyText.indexOf(trimmed)),
1320
+ end: lineEnd,
1321
+ base: bodyStart,
1322
+ text: bodyText,
1323
+ trimmed,
1324
+ rawSlice: rawText.slice(bodyStart, lineEnd),
1325
+ isListItem: true,
1326
+ isTableCell: false,
1327
+ });
1328
+ }
1329
+ } else if (/^\s*\|/.test(lineRaw) && !/^\s*\|[\s:|-]+\|?\s*$/.test(lineRaw)) {
1330
+ let cellPos = 0;
1331
+ while (cellPos < lineProse.length) {
1332
+ const pipeIdx = lineProse.indexOf("|", cellPos);
1333
+ if (pipeIdx === -1) break;
1334
+ const nextPipe = lineProse.indexOf("|", pipeIdx + 1);
1335
+ if (nextPipe === -1) break;
1336
+ const cellRaw = lineProse.slice(pipeIdx + 1, nextPipe);
1337
+ const trimmed = cellRaw.trim();
1338
+ const cjk = (trimmed.match(/[\u4e00-\u9fff]/gu) || []).length;
1339
+ const en = trimmed.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
1340
+ if (cjk >= 15 || en >= 10) {
1341
+ const base = pos + pipeIdx + 1;
1342
+ items.push({
1343
+ start: base + Math.max(0, cellRaw.indexOf(trimmed)),
1344
+ end: pos + nextPipe,
1345
+ base,
1346
+ text: cellRaw,
1347
+ trimmed,
1348
+ rawSlice: rawText.slice(base, pos + nextPipe),
1349
+ isListItem: false,
1350
+ isTableCell: true,
1351
+ });
1352
+ }
1353
+ cellPos = nextPipe;
1354
+ }
1355
+ }
1356
+ if (nl === -1) break;
1357
+ pos = nl + 1;
1358
+ }
1359
+ return items;
1360
+ }
1361
+
589
1362
  /**
590
1363
  * Linear O(n) prose paragraph extractor that cleanly separates Markdown headings/lists/tables
591
1364
  * from immediately-following prose lines while preserving exact offsets in `rawText`.
@@ -638,7 +1411,7 @@ function extractProseParagraphs(proseText, rawText) {
638
1411
  }
639
1412
 
640
1413
  /**
641
- * Linear O(n) sentence splitter with exact source offsets — zero regex backtracking.
1414
+ * Linear O(n) sentence splitter with exact source offsets — decimal/version-safe & zero backtracking.
642
1415
  */
643
1416
  function splitProseSentencesWithOffsets(para) {
644
1417
  const out = [];
@@ -646,7 +1419,6 @@ function splitProseSentencesWithOffsets(para) {
646
1419
  const base = para.base ?? (para.end - text.length);
647
1420
  const n = text.length;
648
1421
  let i = 0;
649
- const isEndPunct = (ch) => ch === "。" || ch === "!" || ch === "?" || ch === "." || ch === "!" || ch === "?";
650
1422
 
651
1423
  while (i < n) {
652
1424
  while (i < n && (text[i] === "\n" || text[i] === "\r" || text[i] === " " || text[i] === "\t")) {
@@ -654,12 +1426,16 @@ function splitProseSentencesWithOffsets(para) {
654
1426
  }
655
1427
  if (i >= n) break;
656
1428
  const segStart = i;
657
- while (i < n && text[i] !== "\n" && !isEndPunct(text[i])) {
1429
+ const startedBold = text.slice(segStart, segStart + 2) === "**";
1430
+ while (i < n && !(isSentenceBreakAt(text, i))) {
658
1431
  i += 1;
659
1432
  }
660
- while (i < n && isEndPunct(text[i])) {
1433
+ while (i < n && text[i] !== "\n" && isSentenceBreakAt(text, i)) {
661
1434
  i += 1;
662
1435
  }
1436
+ if (startedBold && text.slice(i, i + 2) === "**") {
1437
+ i += 2;
1438
+ }
663
1439
  let segEnd = i;
664
1440
  while (segEnd > segStart && (text[segEnd - 1] === " " || text[segEnd - 1] === "\t" || text[segEnd - 1] === "\r")) {
665
1441
  segEnd -= 1;
@@ -674,10 +1450,10 @@ function splitProseSentencesWithOffsets(para) {
674
1450
 
675
1451
  function probeCooccurrenceSlopCluster(proseText, rawText) {
676
1452
  const hits = [];
677
- const paras = extractProseParagraphs(proseText, rawText);
1453
+ const blocks = [...extractProseParagraphs(proseText, rawText), ...extractStructuredProseBlocks(proseText, rawText)];
678
1454
  const enSciRobustRe =
679
1455
  /(?<![A-Za-z0-9_])(?:robust\s+(?:estimator|regression|standard|statistics|variance|backoff|retry|inference|control|error\s+handling|parser|parsing|validation|recovery|fallback)|comprehensive\s+test(?:s|\s+suite)?)(?![A-Za-z0-9_])/gi;
680
- for (const para of paras) {
1456
+ for (const para of blocks) {
681
1457
  const found = new Map();
682
1458
  const paraBase = para.base;
683
1459
  for (const term of ZH_SUBTLE_MARKERS) {
@@ -712,12 +1488,43 @@ function probeCooccurrenceSlopCluster(proseText, rawText) {
712
1488
  return hits;
713
1489
  }
714
1490
 
1491
+ function hasIsomorphicClauseHead(clauses) {
1492
+ const leadVerbs = /^(?:把|将|通过|让|使|对|按|负责|支持|提供|确保|实现|帮助|提升|优化|构建|打造)/u;
1493
+ const keys = [];
1494
+ for (const cl of clauses) {
1495
+ const t = cl.trim().replace(/^[\s*"“「『((]+/, "");
1496
+ if (!t) continue;
1497
+ const vm = t.match(leadVerbs);
1498
+ if (vm) {
1499
+ keys.push(`zhv:${vm[0]}`);
1500
+ continue;
1501
+ }
1502
+ const zhm = t.match(/^[\u4e00-\u9fff]{2}/u);
1503
+ if (zhm) {
1504
+ keys.push(`zh2:${zhm[0]}`);
1505
+ continue;
1506
+ }
1507
+ const enm = t.match(/^([A-Za-z]{2,})/);
1508
+ if (enm) keys.push(`en:${enm[1].toLowerCase()}`);
1509
+ }
1510
+ const counts = new Map();
1511
+ for (const k of keys) {
1512
+ counts.set(k, (counts.get(k) || 0) + 1);
1513
+ if (counts.get(k) >= 2) return true;
1514
+ }
1515
+ return false;
1516
+ }
1517
+
715
1518
  function probeSemicolonTricolon(proseText, rawText) {
716
1519
  const hits = [];
717
- const paras = extractProseParagraphs(proseText, rawText);
1520
+ const blocks = [
1521
+ ...extractProseParagraphs(proseText, rawText),
1522
+ ...extractStructuredProseBlocks(proseText, rawText).filter((b) => b.isListItem),
1523
+ ];
718
1524
  const legalGuard = /(?<![A-Za-z0-9_])(?:shall|must|hereby|pursuant\s+to|provided\s+that)(?![A-Za-z0-9_])|(?:应当|须于|不得|依照)/i;
719
- for (const para of paras) {
720
- // Mask parenthetical citations/quotes at paragraph level so abbreviations like `et al.` never break parens
1525
+ const checklistLeadRe = /^\s*(?:\d+[.)、)]|[((]\d+[))]|第[一二三四五六七八九十\d]+[步项条点]|先|随后|接着|然后|最后|若|如果|当|检查\s*\d|步骤\s*\d|step\s*\d|first\b|then\b|finally\b)/i;
1526
+
1527
+ for (const para of blocks) {
721
1528
  const maskedPara = para.text
722
1529
  .replace(/\([^)\n]*[;;][^)\n]*\)/g, (m) => " ".repeat(m.length))
723
1530
  .replace(/([^)\n]*[;;][^)\n]*)/g, (m) => " ".repeat(m.length))
@@ -730,10 +1537,27 @@ function probeSemicolonTricolon(proseText, rawText) {
730
1537
  if (/^[^;;。!?.!?\n]{2,32}[::]/.test(s.text)) continue;
731
1538
  if (legalGuard.test(s.text)) continue;
732
1539
  const rawSent = rawText.slice(s.start, s.end);
733
- const techRefs = (rawSent.match(/`[^`\n]+`|\]\([^)\n]+\)/g) || []).length;
1540
+ const techRefs = (rawSent.match(/`[^`\n]+`|\]\([^)\n]+\)|<code\b[^>]*>[\s\S]*?<\/code>/gi) || []).length;
734
1541
  if (techRefs >= 2) continue;
735
- const semis = (s.text.match(/[;;]/g) || []).length;
736
- if (semis >= 2) {
1542
+ const clauses = s.text.split(/[;;]/).map((c) => c.trim()).filter(Boolean);
1543
+ if (clauses.length < 3) continue;
1544
+ // Exempt step-by-step checklists or temporal progressions
1545
+ const checklistCount = clauses.filter((c) => checklistLeadRe.test(c)).length;
1546
+ if (checklistCount >= 2) continue;
1547
+ if (/^先/.test(clauses[0]) && clauses.some((c) => /^(?:再|随后|接着|然后|最后)/.test(c))) continue;
1548
+
1549
+ const lens = clauses.map((c) => Math.max(10, countTextUnitsTenths(c)));
1550
+ const mean = lens.reduce((a, b) => a + b, 0) / lens.length;
1551
+ const variance = lens.reduce((a, b) => a + (b - mean) ** 2, 0) / lens.length;
1552
+ const cv = mean > 0 ? Math.sqrt(variance) / mean : 1.0;
1553
+ const iso = hasIsomorphicClauseHead(clauses);
1554
+ if (
1555
+ !iso &&
1556
+ /(?:依赖|共用|失联|期间|否则|除非|仅在|禁止|不新写|不写入|不触发|幂等|持久化)/.test(s.text)
1557
+ ) {
1558
+ continue;
1559
+ }
1560
+ if (cv < 0.28 || (cv < 0.40 && iso)) {
737
1561
  hits.push({ index: s.start, length: Math.min(140, s.text.length) });
738
1562
  }
739
1563
  }
@@ -778,15 +1602,16 @@ function probeRhetoricalQaCadence(proseText, rawText) {
778
1602
 
779
1603
  function probeCommaChainRunon(proseText, rawText) {
780
1604
  const hits = [];
781
- const paras = extractProseParagraphs(proseText, rawText);
782
- for (const para of paras) {
1605
+ const blocks = [
1606
+ ...extractProseParagraphs(proseText, rawText),
1607
+ ...extractStructuredProseBlocks(proseText, rawText).filter((b) => b.isListItem),
1608
+ ];
1609
+ for (const para of blocks) {
783
1610
  const sents = splitProseSentencesWithOffsets(para);
784
1611
  for (const s of sents) {
785
- // Strip numeric thousands separators (1,200) and parenthetical lists before counting commas
786
- const cleaned = s.text
787
- .replace(/(\d),(\d{3})(?!\d)/g, "$1$2")
788
- .replace(/\([^)\n]{1,60}\)/g, " ")
789
- .replace(/([^)\n]{1,60})/g, " ");
1612
+ if (para.isListItem && /`[^`\n]+`/.test(rawText.slice(s.start, s.start + s.text.length))) continue;
1613
+ // Strip numeric thousands separators (1,200) and nested parenthetical lists before counting commas
1614
+ const cleaned = stripParentheticals(s.text.replace(/(\d),(\d{3})(?!\d)/g, "$1$2"));
790
1615
  const commas = (cleaned.match(/[,,]/g) || []).length;
791
1616
  if (commas < 5) continue;
792
1617
  const parts = cleaned.split(/[,,]/).map((p) => p.trim()).filter(Boolean);
@@ -858,8 +1683,12 @@ function probeNarrativeSandwichFrame(proseText, rawText) {
858
1683
 
859
1684
  function classifyOpenerSkeleton(text, explicitOnly = false) {
860
1685
  const s = text.trim();
861
- // Skip key-value metadata lines like "Atomic card: [...]" or "来源:..."
862
- if (/^[A-Za-z][A-Za-z0-9 _-]{1,28}:\s/.test(s) || /^[\u4e00-\u9fff]{2,8}:/.test(s)) {
1686
+ // Skip key-value metadata lines ("Atomic card: [...]", "来源:...") and numbered card headers ("控制栓 01 ...")
1687
+ if (
1688
+ /^[A-Za-z][A-Za-z0-9 _-]{1,28}:\s/.test(s) ||
1689
+ /^[\u4e00-\u9fff]{2,8}:/.test(s) ||
1690
+ /^[\u4e00-\u9fffA-Za-z0-9_-]{2,10}\s*0?\d+(?:\s|$|[·::.-])/.test(s)
1691
+ ) {
863
1692
  return null;
864
1693
  }
865
1694
  if (/^在[\u4e00-\u9fff]{2,6}方面[,,]/.test(s)) return "ZH_ZAI_X_FANGMIAN";
@@ -926,9 +1755,15 @@ function probeTemplateSkeletonEcho(proseText, rawText) {
926
1755
  return false;
927
1756
  }
928
1757
 
1758
+ // Sliding window of 5 adjacent paragraphs so distant unrelated sections never collide
929
1759
  if (paras.length >= 3) {
930
- if (checkItems(paras.map((p) => ({ start: p.start, text: p.trimmed })), false, false)) {
931
- return hits;
1760
+ const paraItems = paras.map((p) => ({ start: p.start, text: p.trimmed }));
1761
+ if (paraItems.length <= 5) {
1762
+ if (checkItems(paraItems, false, false)) return hits;
1763
+ } else {
1764
+ for (let w = 0; w <= paraItems.length - 5; w += 1) {
1765
+ if (checkItems(paraItems.slice(w, w + 5), false, false)) return hits;
1766
+ }
932
1767
  }
933
1768
  }
934
1769
  const allSents = [];
@@ -968,20 +1803,222 @@ function probeLowBurstinessVapor(proseText, rawText) {
968
1803
  return [];
969
1804
  }
970
1805
 
971
- /**
972
- * Compute an explainable 5-axis offline statistical & structural text profile.
973
- * Zero external dependencies; identical math in `src/core.mjs` and `src/dislop/engine.py`.
974
- */
975
- export function analyzeTextProfile(text, { modality = "markdown" } = {}) {
976
- // Normalize CRLF -> LF for statistical calculations so Node and Python agree on Windows files
977
- const raw = String(text || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
978
- const zones = buildZones(raw, modality);
979
- const prose = zones.prose || "";
980
- const paras = extractProseParagraphs(prose, raw);
981
- const sents = [];
982
- for (const para of paras) {
983
- for (const s of splitProseSentencesWithOffsets(para)) {
984
- const u = countTextUnitsTenths(s.text);
1806
+ const ZH_AI_SLOP_JARGON_TERMS = [
1807
+ "全闭环", "形成闭环", "商业闭环", "深度赋能", "全面赋能", "价值跃迁", "范式跃迁", "范式转移",
1808
+ "底层逻辑", "顶层设计", "多维协同", "生态共赢", "无缝衔接", "无缝融合", "丝滑", "满血",
1809
+ "降维打击", "一剑封喉", "一步到位", "心智占领", "颗粒度对齐", "铁律", "彻底根治",
1810
+ "重塑格局", "破局", "降本增效", "护城河", "天花板", "深水区", "王炸", "硬核",
1811
+ "暴雷", "翻车", "崩塌", "雕花", "破框", "无缝", "跃迁",
1812
+ ];
1813
+ const ZH_INDUSTRY_AMBIGUOUS_TERMS = [
1814
+ "闭环", "收口", "兜底", "打通", "落盘", "拉齐", "死线", "根治",
1815
+ ];
1816
+ const ZH_DEV_ZERO_RE = /零(?:幻觉|侵入|摩擦|失误|死角|妥协|门槛|负担|缺陷|暴雷|翻车)/gu;
1817
+ const ZH_DEV_HUA_RE = /(?:体系|精细|常态|全链路|数智|智能|生态|矩阵|范式|极致|平台|中台)化/gu;
1818
+ const ZH_DEV_STORAGE_RE = /WAL|fsync|快照|持久化|落盘到\s*[A-Za-z0-9_./-]+|写入(?:磁盘|日志|文件)|事务日志/i;
1819
+ const ZH_DEV_HARDWARE_CTRL_RE = /(?:位置|速度|电流|力矩|伺服|PID|反馈|外环|内环)闭环|编码器|控制柜/;
1820
+ const ZH_DEV_GROUNDED_FILE_RE = /`[^`\n]+`|[A-Za-z0-9_/-]+\.(?:py|js|ts|mjs|go|rs|sql|json|yaml|yml|log|md)\b/i;
1821
+
1822
+ function probeZhDevJargon(proseText, rawText) {
1823
+ const hits = [];
1824
+ const blocks = [
1825
+ ...extractProseParagraphs(proseText, rawText),
1826
+ ...extractStructuredProseBlocks(proseText, rawText).filter((b) => b.isTableCell),
1827
+ ];
1828
+ for (const para of blocks) {
1829
+ const aiSlopHits = new Map();
1830
+ const industryHits = new Map();
1831
+ const base = para.base;
1832
+ const ctxSlice = para.rawSlice || para.text;
1833
+ const isStorageCtx = ZH_DEV_STORAGE_RE.test(ctxSlice);
1834
+ const isHardwareCtrl = ZH_DEV_HARDWARE_CTRL_RE.test(ctxSlice);
1835
+
1836
+ for (const term of ZH_AI_SLOP_JARGON_TERMS) {
1837
+ const idx = para.text.indexOf(term);
1838
+ if (idx !== -1 && !aiSlopHits.has(term)) {
1839
+ aiSlopHits.set(term, { start: base + idx, end: base + idx + term.length });
1840
+ }
1841
+ }
1842
+ let m;
1843
+ ZH_DEV_ZERO_RE.lastIndex = 0;
1844
+ while ((m = ZH_DEV_ZERO_RE.exec(para.text)) !== null) {
1845
+ if (!aiSlopHits.has(m[0])) aiSlopHits.set(m[0], { start: base + m.index, end: base + m.index + m[0].length });
1846
+ }
1847
+ ZH_DEV_HUA_RE.lastIndex = 0;
1848
+ while ((m = ZH_DEV_HUA_RE.exec(para.text)) !== null) {
1849
+ if (!aiSlopHits.has(m[0])) aiSlopHits.set(m[0], { start: base + m.index, end: base + m.index + m[0].length });
1850
+ }
1851
+
1852
+ for (const term of ZH_INDUSTRY_AMBIGUOUS_TERMS) {
1853
+ if (term === "落盘" && isStorageCtx) continue;
1854
+ if (term === "闭环" && isHardwareCtrl) continue;
1855
+ let coveredByAiTerm = false;
1856
+ for (const aiKey of aiSlopHits.keys()) {
1857
+ if (aiKey.includes(term)) {
1858
+ coveredByAiTerm = true;
1859
+ break;
1860
+ }
1861
+ }
1862
+ if (coveredByAiTerm) continue;
1863
+ const idx = para.text.indexOf(term);
1864
+ if (idx !== -1 && !industryHits.has(term)) {
1865
+ industryHits.set(term, { start: base + idx, end: base + idx + term.length });
1866
+ }
1867
+ }
1868
+
1869
+ const groundedDomain =
1870
+ countConcretenessAnchors(ctxSlice) >= 2 || ZH_DEV_GROUNDED_FILE_RE.test(ctxSlice);
1871
+ let activeSpans = null;
1872
+ if (groundedDomain) {
1873
+ if (aiSlopHits.size >= 3) {
1874
+ activeSpans = Array.from(aiSlopHits.values());
1875
+ }
1876
+ } else if (aiSlopHits.size >= 1 && aiSlopHits.size + industryHits.size >= 3) {
1877
+ activeSpans = [...aiSlopHits.values(), ...industryHits.values()];
1878
+ }
1879
+
1880
+ if (activeSpans && activeSpans.length > 0) {
1881
+ activeSpans.sort((a, b) => a.start - b.start);
1882
+ const first = activeSpans[0].start;
1883
+ const last = activeSpans[activeSpans.length - 1].end;
1884
+ hits.push({ index: first, length: Math.min(140, Math.max(1, last - first)) });
1885
+ }
1886
+ }
1887
+ return hits;
1888
+ }
1889
+
1890
+ const ZH_EXCLAMATION_HYPE_RE = /(?:太棒了|千万不要|一定要|震撼|重磅|惊艳|必看|立即开启|彻底告别|强力推荐|绝对不能|不可错过)/;
1891
+
1892
+ function probeZhExclamation(proseText, rawText) {
1893
+ const allMarks = [];
1894
+ const hypeHits = [];
1895
+ const paras = extractProseParagraphs(proseText, rawText);
1896
+ for (const para of paras) {
1897
+ const trimP = para.trimmed;
1898
+ const paraCjk = (trimP.match(/[\u4e00-\u9fff]/gu) || []).length;
1899
+ // Exempt short standalone taglines (< 20 CJK chars) and example prompt lines
1900
+ if (paraCjk < 20) continue;
1901
+ if (/^(?:示例|例句|提示词|prompt)(?:[\s::]|$)/i.test(trimP)) continue;
1902
+ // Mask quoted speech & parenthetical asides inside paragraph
1903
+ const masked = stripParentheticals(
1904
+ para.text
1905
+ .replace(/“[^”\n]*”/g, (m) => " ".repeat(m.length))
1906
+ .replace(/「[^」\n]*」/g, (m) => " ".repeat(m.length))
1907
+ .replace(/"[^"\n]*"/g, (m) => " ".repeat(m.length))
1908
+ );
1909
+ const maskedPara = { ...para, text: masked };
1910
+ for (const s of splitProseSentencesWithOffsets(maskedPara)) {
1911
+ const re = /[\u4e00-\u9fff][!!]/gu;
1912
+ let m;
1913
+ while ((m = re.exec(s.text)) !== null) {
1914
+ const hit = { index: s.start + m.index, length: m[0].length };
1915
+ allMarks.push(hit);
1916
+ if (ZH_EXCLAMATION_HYPE_RE.test(s.text)) {
1917
+ hypeHits.push(hit);
1918
+ }
1919
+ }
1920
+ }
1921
+ }
1922
+ if (allMarks.length >= 2) return allMarks;
1923
+ return hypeHits;
1924
+ }
1925
+
1926
+ function probeZhMegaSentence(proseText, rawText) {
1927
+ const hits = [];
1928
+ const paras = extractProseParagraphs(proseText, rawText);
1929
+ for (const para of paras) {
1930
+ const paraCjk = (para.text.match(/[\u4e00-\u9fff]/gu) || []).length;
1931
+ const paraSemis = (para.text.match(/[;;]/g) || []).length;
1932
+ const sents = splitProseSentencesWithOffsets(para);
1933
+ let sentHit = false;
1934
+ for (const s of sents) {
1935
+ const sCjk = (s.text.match(/[\u4e00-\u9fff]/gu) || []).length;
1936
+ const visibleCompactedLen = codePointLength(s.text.replace(/[ \t]{2,}/g, " ").trim());
1937
+ if (sCjk > 180 || (sCjk >= 120 && visibleCompactedLen > 180)) {
1938
+ hits.push({ index: s.start, length: Math.min(140, s.text.length) });
1939
+ sentHit = true;
1940
+ }
1941
+ }
1942
+ if (!sentHit && paraCjk > 600 && paraSemis >= 3) {
1943
+ hits.push({ index: para.start, length: Math.min(140, para.trimmed.length) });
1944
+ }
1945
+ }
1946
+ return hits;
1947
+ }
1948
+
1949
+ const UNSOURCED_STAT_MEASUREMENT_RE =
1950
+ /(?:从|由)\s*\d[\d.,]*\S{0,8}(?:到|至|降到|降至|升至|压缩至|缩减至)\s*\d|\bfrom\s+\d[\d.,]*\S{0,8}\s+to\s+\d|(?<![A-Za-z0-9_])(?:n\s*=\s*\d+|benchmark|dataset|sample|audit|log|metric|F1|FPR|Recall|Precision|p95|p99|SLA|SLO|RPO|RTO|uptime|availability|contract|CPU|RAM|memory|disk|coverage|confidence|threshold|CI|eval)(?![A-Za-z0-9_])|(?:实测|压测|基准|抽样|样本|日志|监控|报表|账单|测试集|留出集|置信|阈值|覆盖率|分位|召回|误报|命中|耗时|延迟|错误率|成功率|一致率|配额|折扣|比例|占比|权重|可用率|可用性|增长率|合同|协议|条款)/i;
1951
+
1952
+ const UNSOURCED_STAT_DIRECTIVE_RE =
1953
+ /^\s*(?:Set|Configure|Keep|Ensure|Allow|Leave|Pass|Use|Pick|Select|Adjust|Limit|Clamp|Require|设置|保持|确保|调整|限制|允许|预留)\b|(?:must|should|need\s+to)\s+be\s+(?:at\s+least|no\s+more\s+than|under|over)\b/i;
1954
+
1955
+ function probeUnsourcedStatistic(proseText, rawText, proseMap = null) {
1956
+ const hits = [];
1957
+ const patterns = [
1958
+ /(?:高达|多达|超过|近|约|至少|足足|整整|提升(?:了)?|提高(?:了)?|降低(?:了)?|减少(?:了)?|节省(?:了)?|缩短(?:了)?|增长(?:了)?|暴涨(?:了)?)\s*\d+(?:\.\d+)?%/gu,
1959
+ /\b(?:up\s+to|over|nearly|more\s+than|at\s+least|as\s+much\s+as|by)\s+\d+(?:\.\d+)?%/giu,
1960
+ ];
1961
+ const breaks = buildSentenceBreakIndices(proseText);
1962
+ for (const re of patterns) {
1963
+ let m;
1964
+ while ((m = re.exec(proseText)) !== null) {
1965
+ // Bound check to the enclosing sentence in proseText + corresponding raw slice
1966
+ let left = 0;
1967
+ let right = proseText.length;
1968
+ for (let bIdx = breaks.length - 1; bIdx >= 0; bIdx -= 1) {
1969
+ if (breaks[bIdx] < m.index) {
1970
+ left = breaks[bIdx] + 1;
1971
+ break;
1972
+ }
1973
+ }
1974
+ for (let bIdx = 0; bIdx < breaks.length; bIdx += 1) {
1975
+ if (breaks[bIdx] >= m.index + m[0].length) {
1976
+ right = breaks[bIdx] + 1;
1977
+ break;
1978
+ }
1979
+ }
1980
+ const sentProse = proseText.slice(left, right);
1981
+ if (UNSOURCED_STAT_DIRECTIVE_RE.test(sentProse) && !/(?:提升|提高|降低|减少|节省|缩短|增长|暴涨|faster|improve|reduce|save)/i.test(sentProse)) {
1982
+ continue;
1983
+ }
1984
+ const rawStart = proseMap ? proseMap.starts[left] ?? left : left;
1985
+ const rawEnd = proseMap ? proseMap.ends[Math.max(left, right - 1)] ?? right : right;
1986
+ const win = `${sentProse}\n${rawText.slice(rawStart, rawEnd)}`;
1987
+ const hasSource =
1988
+ /\[\^?\d+\]/.test(win) ||
1989
+ /\]\([^)]+\)/.test(win) ||
1990
+ /https?:\/\//.test(win) ||
1991
+ /\([^()\n]{2,40},\s*(?:19|20)\d{2}[a-z]?\)/.test(win) ||
1992
+ /《[^》\n]{2,30}》/.test(win) ||
1993
+ /(?:见|参见|详见)\s*\[/.test(win) ||
1994
+ UNSOURCED_STAT_MEASUREMENT_RE.test(win);
1995
+ if (!hasSource) {
1996
+ hits.push({ index: m.index, length: m[0].length });
1997
+ }
1998
+ }
1999
+ }
2000
+ return hits;
2001
+ }
2002
+
2003
+ /**
2004
+ * Compute an explainable 5-axis offline statistical & structural text profile.
2005
+ * Zero external dependencies; identical math in `src/core.mjs` and `src/dislop/engine.py`.
2006
+ */
2007
+ export function analyzeTextProfile(text, { modality = "markdown", config = {} } = {}) {
2008
+ // Normalize CRLF -> LF for statistical calculations so Node and Python agree on Windows files
2009
+ const raw = String(text || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
2010
+ const zones = buildZones(raw, modality, {
2011
+ proseFences: config?.proseFences,
2012
+ maskBlockquotes: config?.maskBlockquotes,
2013
+ });
2014
+ const prose = zones.proseLogical ?? zones.prose ?? "";
2015
+ const rawForProbes = zones.proseLogical ? prose : raw;
2016
+ const paras = extractProseParagraphs(prose, rawForProbes);
2017
+ const structBlocks = extractStructuredProseBlocks(prose, rawForProbes);
2018
+ const sents = [];
2019
+ for (const para of paras) {
2020
+ for (const s of splitProseSentencesWithOffsets(para)) {
2021
+ const u = countTextUnitsTenths(s.text);
985
2022
  if (u > 0) sents.push({ ...s, tenths: u });
986
2023
  }
987
2024
  }
@@ -1007,6 +2044,13 @@ export function analyzeTextProfile(text, { modality = "markdown" } = {}) {
1007
2044
  const totalTenths = Math.max(10, countTextUnitsTenths(joinedProse));
1008
2045
  const totalUnits = totalTenths / 10;
1009
2046
 
2047
+ const totalRawChars = codePointLength(raw.replace(/\s+/g, ""));
2048
+ const scannedChars =
2049
+ paras.reduce((acc, p) => acc + codePointLength(p.trimmed.replace(/\s+/g, "")), 0) +
2050
+ structBlocks.reduce((acc, b) => acc + codePointLength(b.trimmed.replace(/\s+/g, "")), 0);
2051
+ const proseCoverage =
2052
+ totalRawChars > 0 ? roundNonNeg(Math.min(1, scannedChars / totalRawChars), 2) : 1;
2053
+
1010
2054
  // Lexical diversity (TTR + Moving-Average TTR window 25 step 5) + bigram echo + char Shannon entropy
1011
2055
  const tokens = (joinedProse.toLowerCase().match(/[\u4e00-\u9fff]|[a-z]{2,}/gu) || []);
1012
2056
  const nTok = tokens.length;
@@ -1048,8 +2092,13 @@ export function analyzeTextProfile(text, { modality = "markdown" } = {}) {
1048
2092
  let maxSemi = 0;
1049
2093
  let maxComma = 0;
1050
2094
  for (const s of sents) {
1051
- const sc = (s.text.replace(/\([^)\n]*[;;][^)\n]*\)/g, " ").match(/[;;]/g) || []).length;
1052
- const cc = (s.text.replace(/(\d),(\d{3})(?!\d)/g, "$1$2").replace(/\([^)\n]{1,60}\)/g, " ").match(/[,,]/g) || []).length;
2095
+ const sc = (
2096
+ s.text
2097
+ .replace(/\([^)\n]*[;;][^)\n]*\)/g, " ")
2098
+ .replace(/([^)\n]*[;;][^)\n]*)/g, " ")
2099
+ .match(/[;;]/g) || []
2100
+ ).length;
2101
+ const cc = (stripParentheticals(s.text.replace(/(\d),(\d{3})(?!\d)/g, "$1$2")).match(/[,,]/g) || []).length;
1053
2102
  if (sc > maxSemi) maxSemi = sc;
1054
2103
  if (cc > maxComma) maxComma = cc;
1055
2104
  }
@@ -1086,6 +2135,7 @@ export function analyzeTextProfile(text, { modality = "markdown" } = {}) {
1086
2135
  sentenceCount: nSents,
1087
2136
  paragraphCount: paras.length,
1088
2137
  unitCount: roundNonNeg(totalUnits, 1),
2138
+ proseCoverage,
1089
2139
  burstiness: {
1090
2140
  meanLength: roundNonNeg(meanLen, 1),
1091
2141
  cv: roundNonNeg(cv, 2),
@@ -1098,6 +2148,7 @@ export function analyzeTextProfile(text, { modality = "markdown" } = {}) {
1098
2148
  bigramEcho: roundNonNeg(bigramEcho, 2),
1099
2149
  charEntropy: roundNonNeg(charEntropy, 2),
1100
2150
  cooccurrenceClusters: coocHits,
2151
+ termConsistencySafe: concretenessStatus === "grounded" && coocHits === 0 && skelHits === 0,
1101
2152
  },
1102
2153
  concreteness: {
1103
2154
  anchorCount,
@@ -1194,9 +2245,16 @@ function probeUiDeadControl(rawText) {
1194
2245
  hits.push({ index: m.index, length: m[0].length, severity: "error" });
1195
2246
  continue;
1196
2247
  }
1197
- const staticDisabled = /\bdisabled(?:\s*=\s*(?:""|"disabled"|'disabled'|\{true\}))?(?=[\s/>]|$)/i.test(attrs);
1198
- const hasReason = /\b(?:title|aria-describedby|data-allow-disabled)\b/i.test(attrs);
1199
- if (staticDisabled && !hasReason) {
2248
+ const staticDisabled = /(?<![A-Za-z0-9_-])disabled(?:\s*=\s*(?:""|"disabled"|'disabled'|"true"|'true'|\{true\}))?(?=[\s/>]|$)/i.test(attrs);
2249
+ const hasReason = /(?<![A-Za-z0-9_-])(?:title|aria-describedby|data-allow-disabled)\s*=/i.test(attrs);
2250
+ const isPagerAction =
2251
+ /(?:^|[\s_-])(?:prev|previous|next|first|last|pager|pagination|page-\d|step-\d|go\s+back|back\s+(?:page|to)|forward)(?=[\s_-]|$)|上一页|下一页|首页|末页|上一步|下一步/i.test(
2252
+ `${attrs.replace(/\bdata-[a-z0-9_-]*title\s*=\s*["'][^"']*["']/gi, "")} ${inner}`
2253
+ );
2254
+ const beforeTagCtx = clean.slice(Math.max(0, m.index - 220), m.index);
2255
+ const inPaginationContainer = /<(?:nav|div|ul|section)\b[^>]*\b(?:aria-label\s*=\s*["'][^"']*pagination|class(?:Name)?\s*=\s*["'][^"']*(?:pagination|pager))/i.test(beforeTagCtx) && !/<\/(?:nav|ul)\b/i.test(beforeTagCtx);
2256
+ const isPagerOrStepper = isPagerAction || inPaginationContainer;
2257
+ if (staticDisabled && !hasReason && !isPagerOrStepper) {
1200
2258
  hits.push({ index: m.index, length: m[0].length, severity: "warning" });
1201
2259
  }
1202
2260
  }
@@ -1227,7 +2285,7 @@ function probeUiAiGradient(rawText) {
1227
2285
  const rgb = parseColorRgb(hx);
1228
2286
  if (!rgb) continue;
1229
2287
  const [h, s] = rgbToHsl(rgb);
1230
- if (h >= 245 && h <= 345 && s >= 45) purplePinkStops += 1;
2288
+ if (h >= 235 && h <= 345 && s >= 45) purplePinkStops += 1;
1231
2289
  }
1232
2290
  const nearSlice = clean.slice(m.index, Math.min(clean.length, m.index + m[0].length + 120));
1233
2291
  const isClipText = /background-clip\s*:\s*text/i.test(nearSlice);
@@ -1235,6 +2293,23 @@ function probeUiAiGradient(rawText) {
1235
2293
  hits.push({ index: m.index, length: m[0].length });
1236
2294
  }
1237
2295
  }
2296
+
2297
+ // 3. SVG <linearGradient> / <radialGradient> with >= 2 purple/indigo/pink stops
2298
+ const svgGradRe = /<(linearGradient|radialGradient)\b[^>]*>([\s\S]*?)<\/\1>/gi;
2299
+ while ((m = svgGradRe.exec(clean)) !== null) {
2300
+ const body = m[2] || "";
2301
+ const colorTokens = body.match(/#[0-9a-fA-F]{3,6}\b|rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)/gi) || [];
2302
+ let purplePinkStops = 0;
2303
+ for (const tok of colorTokens) {
2304
+ const rgb = parseColorRgb(tok);
2305
+ if (!rgb) continue;
2306
+ const [h, s] = rgbToHsl(rgb);
2307
+ if (h >= 235 && h <= 345 && s >= 45) purplePinkStops += 1;
2308
+ }
2309
+ if (purplePinkStops >= 2) {
2310
+ hits.push({ index: m.index, length: m[0].length });
2311
+ }
2312
+ }
1238
2313
  return hits;
1239
2314
  }
1240
2315
 
@@ -1257,13 +2332,64 @@ function probeUiPillSoup(rawText, maxPills = 6) {
1257
2332
  if (wh && wh[1] === wh[2]) continue;
1258
2333
  matches.push({ index: m.index, length: m[0].length });
1259
2334
  }
2335
+
2336
+ // Also detect pill-shaped <rect> elements inside inline <svg> posters/diagrams
2337
+ const svgRe = /<svg\b[^>]*>([\s\S]*?)<\/svg>/gi;
2338
+ while ((m = svgRe.exec(clean)) !== null) {
2339
+ const svgStart = m.index;
2340
+ const svgChunk = m[0];
2341
+ const rectRe = /<rect\b([^>]*)\/?>/gi;
2342
+ let rm;
2343
+ while ((rm = rectRe.exec(svgChunk)) !== null) {
2344
+ const attrs = rm[1] || "";
2345
+ const wm = attrs.match(/(?<![A-Za-z0-9_-])width\s*=\s*["']?(\d+(?:\.\d+)?)/i);
2346
+ const hm = attrs.match(/(?<![A-Za-z0-9_-])height\s*=\s*["']?(\d+(?:\.\d+)?)/i);
2347
+ const rxm = attrs.match(/(?<![A-Za-z0-9_-])r[xy]\s*=\s*["']?(\d+(?:\.\d+)?)/i);
2348
+ if (!wm || !hm || !rxm) continue;
2349
+ const w = Number(wm[1]);
2350
+ const h = Number(hm[1]);
2351
+ const rx = Number(rxm[1]);
2352
+ if (w >= 36 && h >= 14 && h <= 44 && w >= h * 1.5 && rx >= h * 0.35) {
2353
+ matches.push({ index: svgStart + rm.index, length: rm[0].length });
2354
+ }
2355
+ }
2356
+ }
2357
+
1260
2358
  if (matches.length > maxPills) {
2359
+ matches.sort((a, b) => a.index - b.index);
1261
2360
  return [matches[0]];
1262
2361
  }
1263
2362
  return [];
1264
2363
  }
1265
2364
 
2365
+ function extractCssBoxClasses(rawText) {
2366
+ const boxClasses = new Set();
2367
+ const styleRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
2368
+ let sm;
2369
+ while ((sm = styleRe.exec(rawText)) !== null) {
2370
+ const css = sm[1] || "";
2371
+ const ruleRe = /([^{}]+)\{([^{}]+)\}/g;
2372
+ let rm;
2373
+ while ((rm = ruleRe.exec(css)) !== null) {
2374
+ const sel = rm[1] || "";
2375
+ const decl = rm[2] || "";
2376
+ const hasBorderOrShadow =
2377
+ /(?:^|[;\s])(?:border|box-shadow)\s*:\s*(?!none\b|0\b)/i.test(decl) &&
2378
+ !/(?:^|[;\s])border\s*:\s*(?:none|0)\b/i.test(decl);
2379
+ const hasRadius = /(?:^|[;\s])border-radius\s*:\s*(?!0(?:px)?\b)/i.test(decl);
2380
+ const hasPad = /(?:^|[;\s])padding(?:-(?:top|right|bottom|left|inline|block))?\s*:\s*(?!0(?:px)?\b)/i.test(decl);
2381
+ if (hasBorderOrShadow && hasRadius && hasPad) {
2382
+ for (const clsMatch of sel.matchAll(/\.([A-Za-z_-][A-Za-z0-9_-]*)/g)) {
2383
+ boxClasses.add(clsMatch[1]);
2384
+ }
2385
+ }
2386
+ }
2387
+ }
2388
+ return boxClasses;
2389
+ }
2390
+
1266
2391
  function probeUiBoxInBox(rawText) {
2392
+ const boxCssClasses = extractCssBoxClasses(rawText);
1267
2393
  const clean = rawText
1268
2394
  .replace(/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi, preserveLinesBlank)
1269
2395
  .replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
@@ -1288,10 +2414,14 @@ function probeUiBoxInBox(rawText) {
1288
2414
  }
1289
2415
  continue;
1290
2416
  }
1291
- const hasBorderOrShadow = /\b(?:border(?:-[a-z0-9]+)?| ring-1|shadow(?:-[a-z]+)?)\b|border\s*:/i.test(attrs) && !/\bborder-(?:t|b|l|r|0|none)\b/.test(attrs);
2417
+ const clsAttr = attrs.match(/\bclass(?:Name)?\s*=\s*["']([^"']+)["']/i);
2418
+ const hasCssBox = clsAttr ? clsAttr[1].split(/\s+/).some((c) => boxCssClasses.has(c)) : false;
2419
+ const hasBorderOrShadow =
2420
+ (/\b(?:border(?:-[a-z0-9]+)?|ring-1|shadow(?:-[a-z]+)?)\b|border\s*:/i.test(attrs)) &&
2421
+ !/\bborder-(?:t|b|l|r|0|none)\b/i.test(attrs);
1292
2422
  const hasRadius = /\brounded(?:-[a-z0-9]+)?\b|border-radius\s*:/i.test(attrs) && !/\brounded-none\b/.test(attrs);
1293
2423
  const hasPad = /\bp[xy]?-\d|padding\s*:/i.test(attrs);
1294
- const isBox = hasBorderOrShadow && hasRadius && hasPad;
2424
+ const isBox = hasCssBox || (hasBorderOrShadow && hasRadius && hasPad);
1295
2425
  const boxDepth = (stack.length > 0 ? stack[stack.length - 1].boxDepth : 0) + (isBox ? 1 : 0);
1296
2426
 
1297
2427
  if (isBox && boxDepth >= 3 && hits.length === 0) {
@@ -1304,6 +2434,313 @@ function probeUiBoxInBox(rawText) {
1304
2434
  return hits;
1305
2435
  }
1306
2436
 
2437
+ function maskUiVisualMarkup(rawText) {
2438
+ return String(rawText || "")
2439
+ .replace(/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi, preserveLinesBlank)
2440
+ .replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
2441
+ .replace(/\/\*[\s\S]*?\*\//g, preserveLinesBlank)
2442
+ .replace(/<(script|code|pre)\b[^>]*>[\s\S]*?<\/\1>/gi, preserveLinesBlank);
2443
+ }
2444
+
2445
+ function probeUiGlowBlobChrome(rawText) {
2446
+ const clean = maskUiVisualMarkup(rawText);
2447
+ const hits = [];
2448
+ const seen = new Set();
2449
+ const pushHit = (index, length) => {
2450
+ const key = `${index}:${length}`;
2451
+ if (!seen.has(key)) {
2452
+ seen.add(key);
2453
+ hits.push({ index, length });
2454
+ }
2455
+ };
2456
+
2457
+ // 1. Tailwind ambient blur orbs (blur-3xl / blur-[>=40px]) with rounded-full / neon tint / radial-gradient
2458
+ const tagBlurRe = /<[a-zA-Z][a-zA-Z0-9-]*\b[^>]*\b(?:blur-3xl|blur-\[(\d+)px\])[^>]*>/gi;
2459
+ let m;
2460
+ while ((m = tagBlurRe.exec(clean)) !== null) {
2461
+ const px = m[1] ? Number(m[1]) : 64;
2462
+ if (px < 40) continue;
2463
+ const tag = m[0];
2464
+ if (/\b(?:rounded-full|indigo-|purple-|violet-|pink-|fuchsia-|cyan-)\b|radial-gradient/i.test(tag)) {
2465
+ pushHit(m.index, tag.length);
2466
+ }
2467
+ }
2468
+
2469
+ // 2. CSS filter: blur(>=40px) paired with circular / radial-gradient / neon tint
2470
+ const cssBlurRe = /filter\s*:\s*blur\(\s*(\d+)px\s*\)/gi;
2471
+ while ((m = cssBlurRe.exec(clean)) !== null) {
2472
+ if (Number(m[1]) < 40) continue;
2473
+ const winStart = Math.max(0, m.index - 220);
2474
+ const winEnd = Math.min(clean.length, m.index + m[0].length + 220);
2475
+ const ctx = clean.slice(winStart, winEnd);
2476
+ if (/border-radius\s*:\s*(?:50%|999\d*px)|radial-gradient|#[0-9a-fA-F]{6}/i.test(ctx)) {
2477
+ pushHit(m.index, m[0].length);
2478
+ }
2479
+ }
2480
+
2481
+ // 3. Neon colored shadow glow (Tailwind or CSS box-shadow)
2482
+ const twShadowRe = /\bshadow-(?:indigo|purple|violet|pink|fuchsia|cyan)-[45]00(?:\/\d+)?\b/gi;
2483
+ while ((m = twShadowRe.exec(clean)) !== null) {
2484
+ pushHit(m.index, m[0].length);
2485
+ }
2486
+ const cssShadowRe = /box-shadow\s*:[^;\n]{0,160}/gi;
2487
+ while ((m = cssShadowRe.exec(clean)) !== null) {
2488
+ const decl = m[0];
2489
+ if (!/\b(?:1[5-9]|[2-9]\d)px\b/.test(decl)) continue;
2490
+ const colMatches = decl.match(/#[0-9a-fA-F]{3,6}\b|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}[^)]*\)/gi) || [];
2491
+ for (const cTok of colMatches) {
2492
+ const rgbMatch = cTok.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/i);
2493
+ const rgb = rgbMatch ? [Number(rgbMatch[1]), Number(rgbMatch[2]), Number(rgbMatch[3])] : parseColorRgb(cTok);
2494
+ if (!rgb) continue;
2495
+ const [h, s] = rgbToHsl(rgb);
2496
+ if (s >= 55 && ((h >= 175 && h <= 210) || (h >= 245 && h <= 345))) {
2497
+ pushHit(m.index, decl.length);
2498
+ break;
2499
+ }
2500
+ }
2501
+ }
2502
+
2503
+ // 4. Pulsing badge dot (`animate-ping` in `rounded-full`)
2504
+ const pingRe = /<[^>]*\banimate-ping\b[^>]*>/gi;
2505
+ while ((m = pingRe.exec(clean)) !== null) {
2506
+ const ctx = clean.slice(Math.max(0, m.index - 140), Math.min(clean.length, m.index + m[0].length + 140));
2507
+ if (/\brounded-full\b/.test(ctx)) {
2508
+ pushHit(m.index, m[0].length);
2509
+ }
2510
+ }
2511
+
2512
+ // 5. SVG excessive glow / drop-shadow filters
2513
+ const svgRe = /<svg\b[^>]*>[\s\S]*?<\/svg>/gi;
2514
+ while ((m = svgRe.exec(clean)) !== null) {
2515
+ const svgBody = m[0];
2516
+ const blurTags = svgBody.match(/<(?:feGaussianBlur|feDropShadow)\b/gi) || [];
2517
+ const heavyBlur = /<(?:feGaussianBlur|feDropShadow)\b[^>]*\bstdDeviation\s*=\s*["']\s*(?:[89]|\d{2,})(?:\.\d+)?/i.test(svgBody);
2518
+ if (blurTags.length >= 2 || heavyBlur) {
2519
+ const firstFilter = svgBody.match(/<(?:feGaussianBlur|feDropShadow)\b[^>]*>/i);
2520
+ const idx = firstFilter ? m.index + svgBody.indexOf(firstFilter[0]) : m.index;
2521
+ const len = firstFilter ? firstFilter[0].length : 32;
2522
+ pushHit(idx, len);
2523
+ }
2524
+ }
2525
+
2526
+ return hits;
2527
+ }
2528
+
2529
+ function probeUiEmojiIconChrome(rawText) {
2530
+ const clean = maskUiVisualMarkup(rawText).replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, preserveLinesBlank);
2531
+ const emojiClass = "[\\u{1F680}\\u2728\\u26A1\\u{1F525}\\u{1F4A1}\\u{1F3AF}\\u{1F6E1}\\u2699\\u{1F4C8}\\u{1F916}\\u{1F48E}\\u{1F31F}\\u{1F3A8}\\u{1F512}\\u{1F4CA}\\u{1F9E0}\\u{1F310}\\u{1F389}]\\uFE0F?";
2532
+ const tagRe = new RegExp(`<(h[1-4]|button|a|span|div|text)\\b[^>]*>[^<]{0,90}${emojiClass}[^<]{0,90}<\\/\\1>`, "giu");
2533
+ const matches = [];
2534
+ let m;
2535
+ while ((m = tagRe.exec(clean)) !== null) {
2536
+ matches.push({ index: m.index, length: m[0].length });
2537
+ }
2538
+ if (matches.length >= 3) {
2539
+ return [matches[0]];
2540
+ }
2541
+ return [];
2542
+ }
2543
+
2544
+ function probeUiTemplateCardGrid(rawText) {
2545
+ const clean = maskUiVisualMarkup(rawText)
2546
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, preserveLinesBlank)
2547
+ .replace(/<svg\b[^>]*>[\s\S]*?<\/svg>/gi, preserveLinesBlank);
2548
+ const hits = [];
2549
+
2550
+ // 1. >= 3 tinted rounded-square icon tiles
2551
+ const tileRe = /<(div|span)\b([^>]*)>/gi;
2552
+ const tileHits = [];
2553
+ let m;
2554
+ while ((m = tileRe.exec(clean)) !== null) {
2555
+ const attrs = m[2] || "";
2556
+ const hasRound = /\brounded-(?:lg|xl|2xl)\b/.test(attrs);
2557
+ const hasSize =
2558
+ /\bsize-(?:8|9|10|11|12|14|16)\b/.test(attrs) ||
2559
+ (/\bw-(?:8|9|10|11|12|14|16)\b/.test(attrs) && /\bh-(?:8|9|10|11|12|14|16)\b/.test(attrs));
2560
+ const hasTint = /\bbg-(?:indigo|purple|violet|blue|pink|fuchsia|emerald|teal|cyan|amber|orange|rose)-(?:50|100|400\/\d+|500\/\d+|900\/\d+|950\/\d+)\b/.test(attrs);
2561
+ if (hasRound && hasSize && hasTint) {
2562
+ tileHits.push({ index: m.index, length: m[0].length });
2563
+ }
2564
+ }
2565
+ if (tileHits.length >= 3) {
2566
+ hits.push(tileHits[0]);
2567
+ }
2568
+
2569
+ // 2. Fake macOS 3-dot traffic-light window chrome
2570
+ const dotRe = /<(?:span|div)\b[^>]*\brounded-full\b[^>]*\bbg-(red|rose|yellow|amber|green|emerald)-\d{2,3}\b[^>]*>(?:\s*<\/(?:span|div)>)?/gi;
2571
+ const dots = [];
2572
+ while ((m = dotRe.exec(clean)) !== null) {
2573
+ dots.push({ index: m.index, length: m[0].length, color: m[1].toLowerCase() });
2574
+ }
2575
+ for (let i = 0; i + 2 < dots.length; i += 1) {
2576
+ const a = dots[i];
2577
+ const b = dots[i + 1];
2578
+ const c = dots[i + 2];
2579
+ if (
2580
+ (a.color === "red" || a.color === "rose") &&
2581
+ (b.color === "yellow" || b.color === "amber") &&
2582
+ (c.color === "green" || c.color === "emerald") &&
2583
+ c.index - a.index <= 280
2584
+ ) {
2585
+ hits.push({ index: a.index, length: Math.min(120, c.index + c.length - a.index) });
2586
+ break;
2587
+ }
2588
+ }
2589
+
2590
+ // 3. Sequential standalone zero-padded eyebrow kickers (`01`, `02`, `03`)
2591
+ // Exempt semantic ordered lists / navigation (`<ol>`, `role="list"`, `<nav>`) via tag nesting stack
2592
+ const VOID_HTML_TAGS = new Set([
2593
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
2594
+ "link", "meta", "param", "source", "track", "wbr",
2595
+ ]);
2596
+ const listAncestryRanges = [];
2597
+ const listTagStack = [];
2598
+ const tokListRe = /<\/?([a-zA-Z0-9-]+)\b([^>]*)\/?>/g;
2599
+ while ((m = tokListRe.exec(clean)) !== null) {
2600
+ const full = m[0];
2601
+ const tag = m[1].toLowerCase();
2602
+ const attrs = m[2] || "";
2603
+ const selfClose = full.endsWith("/>") || VOID_HTML_TAGS.has(tag);
2604
+ if (full.startsWith("</")) {
2605
+ for (let i = listTagStack.length - 1; i >= 0; i -= 1) {
2606
+ if (listTagStack[i].tag === tag) {
2607
+ const popped = listTagStack.splice(i);
2608
+ for (const item of popped) {
2609
+ if (item.isList) listAncestryRanges.push([item.start, m.index + full.length]);
2610
+ }
2611
+ break;
2612
+ }
2613
+ }
2614
+ continue;
2615
+ }
2616
+ const isListContainer =
2617
+ tag === "ol" ||
2618
+ tag === "nav" ||
2619
+ /(?<![A-Za-z0-9_-])role\s*=\s*["']list["']/i.test(attrs);
2620
+ if (!selfClose) {
2621
+ listTagStack.push({ tag, isList: isListContainer, start: m.index });
2622
+ }
2623
+ }
2624
+ for (const item of listTagStack) {
2625
+ if (item.isList) listAncestryRanges.push([item.start, clean.length]);
2626
+ }
2627
+ const inSemanticList = (idx) => listAncestryRanges.some(([s, e]) => idx >= s && idx <= e);
2628
+
2629
+ const numTagRe = /<(span|div|p)\b[^>]*>\s*(0[1-9])\s*<\/\1>/gi;
2630
+ const seqTags = [];
2631
+ while ((m = numTagRe.exec(clean)) !== null) {
2632
+ if (inSemanticList(m.index)) continue;
2633
+ seqTags.push({ index: m.index, length: m[0].length, num: m[2] });
2634
+ }
2635
+ const seqNums = new Set(seqTags.map((t) => t.num));
2636
+ if (seqTags.length >= 3 && seqNums.has("01") && seqNums.has("02") && seqNums.has("03")) {
2637
+ hits.push({ index: seqTags[0].index, length: seqTags[0].length });
2638
+ }
2639
+
2640
+ return hits;
2641
+ }
2642
+
2643
+ function probeSvgLayoutSlop(rawText) {
2644
+ const clean = maskUiVisualMarkup(rawText).replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, preserveLinesBlank);
2645
+ const hits = [];
2646
+
2647
+ // 1. Non-icon <svg> missing viewBox
2648
+ const svgOpenRe = /<svg\b([^>]*)>/gi;
2649
+ let m;
2650
+ while ((m = svgOpenRe.exec(clean)) !== null) {
2651
+ const attrs = m[1] || "";
2652
+ if (/\bviewBox\s*=/i.test(attrs)) continue;
2653
+ const wm = attrs.match(/\bwidth\s*=\s*["']?(\d+(?:\.\d+)?)/i);
2654
+ const hm = attrs.match(/\bheight\s*=\s*["']?(\d+(?:\.\d+)?)/i);
2655
+ if (wm && hm && Number(wm[1]) >= 120 && Number(hm[1]) >= 80) {
2656
+ hits.push({ index: m.index, length: m[0].length });
2657
+ }
2658
+ }
2659
+
2660
+ // 2. Overlapping <text x="..." y="..."> coordinates within the same <g> transform scope
2661
+ const svgTokRe = /<\/?(?:g|text)\b[^>]*>|[^<]+/gi;
2662
+ const gStack = [];
2663
+ const textsByGroup = new Map();
2664
+ let inText = false;
2665
+ let curTextInfo = null;
2666
+ let curTextBody = "";
2667
+ while ((m = svgTokRe.exec(clean)) !== null) {
2668
+ const tok = m[0];
2669
+ if (/^<g\b/i.test(tok)) {
2670
+ const tr = tok.match(/\btransform\s*=\s*["']([^"']+)["']/i);
2671
+ gStack.push(tr ? tr[1].trim() : "");
2672
+ continue;
2673
+ }
2674
+ if (/^<\/g>/i.test(tok)) {
2675
+ if (gStack.length > 0) gStack.pop();
2676
+ continue;
2677
+ }
2678
+ if (/^<text\b/i.test(tok)) {
2679
+ const xm = tok.match(/\bx\s*=\s*["']?(-?\d+(?:\.\d+)?)/i);
2680
+ const ym = tok.match(/\by\s*=\s*["']?(-?\d+(?:\.\d+)?)/i);
2681
+ if (xm && ym && !/\/>$/.test(tok)) {
2682
+ inText = true;
2683
+ curTextBody = "";
2684
+ curTextInfo = {
2685
+ index: m.index,
2686
+ length: tok.length,
2687
+ x: Number(xm[1]),
2688
+ y: Number(ym[1]),
2689
+ groupKey: gStack.filter(Boolean).join("|") || "root",
2690
+ };
2691
+ }
2692
+ continue;
2693
+ }
2694
+ if (/^<\/text>/i.test(tok)) {
2695
+ if (inText && curTextInfo && curTextBody.trim().length > 0) {
2696
+ const list = textsByGroup.get(curTextInfo.groupKey) || [];
2697
+ list.push(curTextInfo);
2698
+ textsByGroup.set(curTextInfo.groupKey, list);
2699
+ }
2700
+ inText = false;
2701
+ curTextInfo = null;
2702
+ continue;
2703
+ }
2704
+ if (inText) {
2705
+ curTextBody += tok.replace(/<[^>]+>/g, "");
2706
+ }
2707
+ }
2708
+ for (const list of textsByGroup.values()) {
2709
+ let foundOverlap = false;
2710
+ for (let i = 0; i < list.length && !foundOverlap; i += 1) {
2711
+ for (let j = i + 1; j < list.length; j += 1) {
2712
+ if (Math.abs(list[i].x - list[j].x) < 8 && Math.abs(list[i].y - list[j].y) < 8) {
2713
+ hits.push({ index: list[j].index, length: list[j].length });
2714
+ foundOverlap = true;
2715
+ break;
2716
+ }
2717
+ }
2718
+ }
2719
+ }
2720
+
2721
+ // 3. >= 2 orphaned unused id="..." entries inside <defs>
2722
+ const defsRe = /<defs\b[^>]*>([\s\S]*?)<\/defs>/gi;
2723
+ while ((m = defsRe.exec(clean)) !== null) {
2724
+ const defsBody = m[1] || "";
2725
+ const outsideDefs = clean.slice(0, m.index) + clean.slice(m.index + m[0].length);
2726
+ const idMatches = [...defsBody.matchAll(/\bid\s*=\s*["']([^"']+)["']/gi)];
2727
+ let orphanCount = 0;
2728
+ for (const im of idMatches) {
2729
+ const defId = im[1];
2730
+ const escaped = defId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2731
+ const usedRe = new RegExp(`#${escaped}(?![A-Za-z0-9_-])`);
2732
+ if (!usedRe.test(outsideDefs) && !usedRe.test(defsBody.replace(im[0], ""))) {
2733
+ orphanCount += 1;
2734
+ }
2735
+ }
2736
+ if (orphanCount >= 2) {
2737
+ hits.push({ index: m.index, length: Math.min(80, m[0].length) });
2738
+ }
2739
+ }
2740
+
2741
+ return hits;
2742
+ }
2743
+
1307
2744
  function normalizeAsciiDigits(str) {
1308
2745
  return String(str || "").replace(/[0-9]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0));
1309
2746
  }
@@ -1340,30 +2777,159 @@ function probeUnanchoredMultiplier(zoneText, rawText) {
1340
2777
 
1341
2778
  // ---------- Core Text Auditor ----------
1342
2779
 
1343
- export function auditText(text, { filename = "<memory>", modality = null, pack, config = {}, allowSyntheticFixtures = false } = {}) {
2780
+ const META_MENTION_GUARD_RULES = new Set([
2781
+ "unsubstantiated-superlative",
2782
+ "reg-unsubstantiated-superlative",
2783
+ "false-certainty",
2784
+ "overclaiming",
2785
+ "unanchored-multiplier",
2786
+ "unsourced-attribution",
2787
+ ]);
2788
+
2789
+ function isMetaMentionHit(clauseSource, start, end, rule, breakIndices = null) {
2790
+ const fam = String(rule.family || "");
2791
+ const unprefixedId = String(rule.id || "").replace(/^(?:reg|eng|biz|ess|lit|exec|ui)-/, "");
2792
+ if (
2793
+ rule.category !== "lexicon" &&
2794
+ !fam.startsWith("lexicon/") &&
2795
+ !META_MENTION_GUARD_RULES.has(rule.id) &&
2796
+ !META_MENTION_GUARD_RULES.has(unprefixedId)
2797
+ ) {
2798
+ return false;
2799
+ }
2800
+ const s = String(clauseSource || "");
2801
+ let left = s.lastIndexOf("\n", Math.max(0, start - 1)) + 1;
2802
+ let right = s.indexOf("\n", end);
2803
+ if (right === -1) right = s.length;
2804
+ if (Array.isArray(breakIndices) && breakIndices.length > 0) {
2805
+ for (let bIdx = breakIndices.length - 1; bIdx >= 0; bIdx -= 1) {
2806
+ if (breakIndices[bIdx] < start) {
2807
+ left = Math.max(left, breakIndices[bIdx] + 1);
2808
+ break;
2809
+ }
2810
+ }
2811
+ for (let bIdx = 0; bIdx < breakIndices.length; bIdx += 1) {
2812
+ if (breakIndices[bIdx] >= end) {
2813
+ right = Math.min(right, breakIndices[bIdx]);
2814
+ break;
2815
+ }
2816
+ }
2817
+ } else {
2818
+ let p = start;
2819
+ while (p > left && !isSentenceBreakAt(s, p - 1)) p -= 1;
2820
+ left = p;
2821
+ p = end;
2822
+ while (p < right && !isSentenceBreakAt(s, p)) p += 1;
2823
+ right = p;
2824
+ }
2825
+ const clause = s.slice(left, right);
2826
+
2827
+ const hasMetaCue =
2828
+ /(?:禁用|禁词|忌用|黑词|黑话|套话|套词|违禁|回避|勿用|避免(?:使用)?|替换为|改为|改成|改写|反例|原句|例句|示例|(?:这类|这种|这几个|等)(?:词|套话|套词|表达|说法)|(?:最好|尽量|切忌|千万)?(?:别用|不要用|少用|慎用|不用)|forbidden|banned|avoid|do\s+not\s+use|replace\s+with|instead\s+of|(?:phrases?|terms?|words?)\s+(?:like|such\s+as)|anti-pattern|clich[eé]|slop|buzzwords?|jargon|filler)/i.test(
2829
+ clause
2830
+ ) || /(?:^|\b)(?:FORBIDDEN|BANNED|DISALLOWED|BLOCKLIST|STOP_WORDS)\s*[:=]/i.test(clause);
2831
+ if (!hasMetaCue) return false;
2832
+
2833
+ const quotePairs = [
2834
+ ['"', '"'],
2835
+ ["“", "”"],
2836
+ ["‘", "’"],
2837
+ ["「", "」"],
2838
+ ["『", "』"],
2839
+ ["`", "`"],
2840
+ ["'", "'"],
2841
+ ];
2842
+ const relStart = start - left;
2843
+ const relEnd = end - left;
2844
+ for (const [openQ, closeQ] of quotePairs) {
2845
+ const qOpen = clause.lastIndexOf(openQ, Math.max(0, relStart));
2846
+ if (qOpen === -1 || relStart - qOpen > 24) continue;
2847
+ const qClose = clause.indexOf(closeQ, relEnd);
2848
+ if (qClose === -1) continue;
2849
+ if (qClose - qOpen <= 48) {
2850
+ return true;
2851
+ }
2852
+ }
2853
+ return false;
2854
+ }
2855
+
2856
+ function cleanMatchExcerpt(matchedRaw, modality, primaryZoneName) {
2857
+ let out = String(matchedRaw || "");
2858
+ if (primaryZoneName === "prose" && (modality === "html" || modality === "jsx" || modality === "svg")) {
2859
+ const noTags = out.replace(/<[^>]+>/g, " ");
2860
+ const decoded = noTags.replace(HTML_ENTITY_RE, (m, dec, hex) => decodeEntityToken(m, dec, hex) || m);
2861
+ const stripped = decodeXmlEntities(decoded).replace(/\s+/g, " ").trim();
2862
+ if (stripped) out = stripped;
2863
+ } else {
2864
+ out = out.replace(/\s+/g, " ").trim();
2865
+ }
2866
+ if (/^\*\*[^*]+$/.test(out)) out = out.slice(2).trim();
2867
+ if (/^[^*]+\*\*$/.test(out)) out = out.slice(0, -2).trim();
2868
+ return clipCodepoints(out, 140);
2869
+ }
2870
+
2871
+ export function auditText(text, { filename = "<memory>", modality = null, pack, config = {}, allowSyntheticFixtures = false, register = null } = {}) {
1344
2872
  const mod = modality || detectModality(filename) || "markdown";
1345
2873
  const lineStarts = buildLineStarts(text);
1346
- const zones = buildZones(text, mod);
2874
+ const zones = buildZones(text, mod, {
2875
+ proseFences: config?.proseFences,
2876
+ maskBlockquotes: config?.maskBlockquotes,
2877
+ });
1347
2878
  const { byTargetLine, directives } = parseSuppressions(text);
1348
2879
  const allowList = config?.allow || [];
1349
- const cpPrefix = /[\uD800-\uDBFF]/.test(text) ? buildCodePointPrefix(text) : null;
2880
+ const cpPrefix = /[\uD800-\uDFFF]/.test(text) ? buildCodePointPrefix(text) : null;
2881
+ const textBreaks = buildSentenceBreakIndices(text);
2882
+ const rawProseMaskBreaks = zones.prose ? buildSentenceBreakIndices(zones.prose) : textBreaks;
2883
+ const regInfo = resolveRegister(text, { filename, flagRegister: register, config });
2884
+ const allowHtmlRulesInMixedMd = mod === "markdown" && hasEmbeddedUiMarkup(text);
2885
+ const mdUiZone = allowHtmlRulesInMixedMd ? maskMarkdownFences(text, new Set()).replace(/`[^`\n]+`/g, (m) => " ".repeat(m.length)) : null;
1350
2886
  const findings = [];
1351
2887
 
1352
- for (const rule of pack.rules || []) {
1353
- if (rule.modalities && !rule.modalities.includes(mod)) continue;
2888
+ for (const baseRule of pack.rules || []) {
2889
+ const directModMatch = !baseRule.modalities || baseRule.modalities.includes(mod);
2890
+ const mixedUiRule = !directModMatch && allowHtmlRulesInMixedMd && baseRule.modalities.includes("html");
2891
+ if (!directModMatch && !mixedUiRule) continue;
1354
2892
 
1355
- // Synthetic Office/PDF fixture tokens ONLY during `dislop pack-test`
1356
- if (allowSyntheticFixtures && (text.startsWith("DOCX_") || text.startsWith("PPTX_"))) {
2893
+ const regApplied = applyRegisterOverride(baseRule, regInfo.register, config);
2894
+ if (regApplied.skip) {
2895
+ for (const d of directives) {
2896
+ if (!d.used && d.ruleIds.includes(baseRule.id)) {
2897
+ d.used = true;
2898
+ }
2899
+ }
2900
+ continue;
2901
+ }
2902
+ const rule = regApplied.rule;
2903
+ const registerAdjusted = regApplied.registerAdjusted;
2904
+
2905
+ // Synthetic Office/Image/PDF fixture tokens ONLY during `dislop pack-test`
2906
+ if (
2907
+ allowSyntheticFixtures &&
2908
+ (text.startsWith("DOCX_") || text.startsWith("PPTX_") || text.startsWith("IMG_") || text.startsWith("PDF_"))
2909
+ ) {
1357
2910
  const synthHits = evaluateSyntheticBinaryFixture(text, rule, pack.thresholds || {});
1358
2911
  for (const h of synthHits) {
1359
- findings.push(makeFinding({ rule, filename, modality: mod, location: h.location, match: h.match, sentence: text, span: { start: 0, end: text.length } }));
2912
+ findings.push(
2913
+ makeFinding({
2914
+ rule: h.severity ? { ...rule, severity: h.severity } : rule,
2915
+ filename,
2916
+ modality: mod,
2917
+ location: h.location,
2918
+ match: h.match,
2919
+ sentence: text,
2920
+ span: { start: 0, end: text.length },
2921
+ registerAdjusted,
2922
+ })
2923
+ );
1360
2924
  }
1361
2925
  continue;
1362
2926
  }
1363
2927
 
1364
2928
  let rawHits = [];
1365
2929
  const primaryZoneName = (rule.zones && rule.zones[0]) || "prose";
1366
- const zoneText = zones[primaryZoneName] ?? zones.prose;
2930
+ const useLogicalProse = !mixedUiRule && primaryZoneName === "prose" && zones.proseLogical && zones.proseMap;
2931
+ const zoneText = mixedUiRule ? mdUiZone : (useLogicalProse ? zones.proseLogical : (zones[primaryZoneName] ?? zones.prose));
2932
+ const rawForProbes = useLogicalProse ? zoneText : text;
1367
2933
 
1368
2934
  if (rule.probe === "regex") {
1369
2935
  for (const pattern of rule.patterns || []) {
@@ -1383,15 +2949,15 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1383
2949
  len -= lead[0].length;
1384
2950
  }
1385
2951
  }
1386
- while (len > 1 && text.charCodeAt(idx) === 0xfeff) {
2952
+ while (len > 1 && zoneText.charCodeAt(idx) === 0xfeff) {
1387
2953
  idx += 1;
1388
2954
  len -= 1;
1389
2955
  }
1390
2956
  if (
1391
2957
  rule.id === "unfilled-placeholder" &&
1392
- text[idx] === "[" &&
1393
- text[idx + len - 1] === "]" &&
1394
- /^(?:\(|\[|:)/.test(text.slice(idx + len))
2958
+ zoneText[idx] === "[" &&
2959
+ zoneText[idx + len - 1] === "]" &&
2960
+ /^(?:\(|\[|:)/.test(zoneText.slice(idx + len))
1395
2961
  ) {
1396
2962
  continue;
1397
2963
  }
@@ -1399,35 +2965,43 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1399
2965
  }
1400
2966
  }
1401
2967
  } else if (rule.probe === "negation-pivot") {
1402
- rawHits = probeNegationPivot(zoneText, text);
2968
+ rawHits = probeNegationPivot(zoneText, rawForProbes);
1403
2969
  } else if (rule.probe === "staccato-run") {
1404
2970
  rawHits = probeStaccatoRun(zoneText);
1405
2971
  } else if (rule.probe === "zh-four-char-triad") {
1406
2972
  rawHits = probeZhFourCharTriad(zoneText);
1407
2973
  } else if (rule.probe === "unsourced-attribution") {
1408
- rawHits = probeUnsourcedAttribution(zoneText, text);
2974
+ rawHits = probeUnsourcedAttribution(zoneText, rawForProbes);
1409
2975
  } else if (rule.probe === "bold-lead-list-wall") {
1410
- rawHits = probeBoldLeadListWall(zoneText, text, pack.thresholds?.boldLeadListRun || 4);
2976
+ rawHits = probeBoldLeadListWall(zoneText, rawForProbes, pack.thresholds?.boldLeadListRun || 4);
1411
2977
  } else if (rule.probe === "em-dash-density") {
1412
2978
  rawHits = probeEmDashDensity(zoneText, pack.thresholds?.maxEmDashesPer300Words || 4);
1413
2979
  } else if (rule.probe === "zh-halfwidth-punctuation") {
1414
2980
  rawHits = probeZhHalfwidthPunctuation(zoneText);
1415
2981
  } else if (rule.probe === "cooccurrence-slop-cluster") {
1416
- rawHits = probeCooccurrenceSlopCluster(zoneText, text);
2982
+ rawHits = probeCooccurrenceSlopCluster(zoneText, rawForProbes);
1417
2983
  } else if (rule.probe === "semicolon-tricolon") {
1418
- rawHits = probeSemicolonTricolon(zoneText, text);
2984
+ rawHits = probeSemicolonTricolon(zoneText, rawForProbes);
1419
2985
  } else if (rule.probe === "rhetorical-qa-cadence") {
1420
- rawHits = probeRhetoricalQaCadence(zoneText, text);
2986
+ rawHits = probeRhetoricalQaCadence(zoneText, rawForProbes);
1421
2987
  } else if (rule.probe === "comma-chain-runon") {
1422
- rawHits = probeCommaChainRunon(zoneText, text);
2988
+ rawHits = probeCommaChainRunon(zoneText, rawForProbes);
1423
2989
  } else if (rule.probe === "narrative-sandwich-frame") {
1424
- rawHits = probeNarrativeSandwichFrame(zoneText, text);
2990
+ rawHits = probeNarrativeSandwichFrame(zoneText, rawForProbes);
1425
2991
  } else if (rule.probe === "template-skeleton-echo") {
1426
- rawHits = probeTemplateSkeletonEcho(zoneText, text);
2992
+ rawHits = probeTemplateSkeletonEcho(zoneText, rawForProbes);
1427
2993
  } else if (rule.probe === "low-burstiness-vapor") {
1428
- rawHits = probeLowBurstinessVapor(zoneText, text);
2994
+ rawHits = probeLowBurstinessVapor(zoneText, rawForProbes);
1429
2995
  } else if (rule.probe === "unanchored-multiplier") {
1430
- rawHits = probeUnanchoredMultiplier(zoneText, text);
2996
+ rawHits = probeUnanchoredMultiplier(zoneText, rawForProbes);
2997
+ } else if (rule.probe === "zh-dev-jargon") {
2998
+ rawHits = probeZhDevJargon(zoneText, rawForProbes);
2999
+ } else if (rule.probe === "zh-exclamation") {
3000
+ rawHits = probeZhExclamation(zoneText, rawForProbes);
3001
+ } else if (rule.probe === "zh-mega-sentence") {
3002
+ rawHits = probeZhMegaSentence(zoneText, rawForProbes);
3003
+ } else if (rule.probe === "unsourced-statistic") {
3004
+ rawHits = probeUnsourcedStatistic(zoneText, text, useLogicalProse ? zones.proseMap : null);
1431
3005
  } else if (rule.probe === "ui-dead-control") {
1432
3006
  rawHits = probeUiDeadControl(text);
1433
3007
  } else if (rule.probe === "ui-ai-gradient") {
@@ -1436,9 +3010,24 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1436
3010
  rawHits = probeUiPillSoup(text, pack.thresholds?.maxPillsPerFile || 6);
1437
3011
  } else if (rule.probe === "ui-box-in-box") {
1438
3012
  rawHits = probeUiBoxInBox(text);
3013
+ } else if (rule.probe === "ui-glow-blob-chrome") {
3014
+ rawHits = probeUiGlowBlobChrome(text);
3015
+ } else if (rule.probe === "ui-emoji-icon-chrome") {
3016
+ rawHits = probeUiEmojiIconChrome(text);
3017
+ } else if (rule.probe === "ui-template-card-grid") {
3018
+ rawHits = probeUiTemplateCardGrid(text);
3019
+ } else if (rule.probe === "svg-layout-slop") {
3020
+ rawHits = probeSvgLayoutSlop(text);
1439
3021
  }
1440
3022
 
1441
3023
  // Sort and deduplicate overlapping spans emitted by multiple patterns of the same rule
3024
+ if (useLogicalProse) {
3025
+ rawHits = rawHits.map((h) => {
3026
+ const sIdx = zones.proseMap.starts[h.index] ?? h.index;
3027
+ const eIdx = zones.proseMap.ends[Math.max(h.index, h.index + h.length - 1)] ?? h.index + h.length;
3028
+ return { ...h, index: sIdx, length: Math.max(1, eIdx - sIdx) };
3029
+ });
3030
+ }
1442
3031
  rawHits.sort((a, b) => a.index - b.index || b.length - a.length);
1443
3032
  const dedupHits = [];
1444
3033
  for (const h of rawHits) {
@@ -1451,7 +3040,11 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1451
3040
  const start = hit.index;
1452
3041
  const end = hit.index + hit.length;
1453
3042
  const matchedRaw = text.slice(start, end);
1454
- if (isAllowedMatch(matchedRaw, allowList)) continue;
3043
+ const matchedDisplay = cleanMatchExcerpt(matchedRaw, mod, primaryZoneName);
3044
+ if (isAllowedMatch(matchedRaw, allowList) || isAllowedMatch(matchedDisplay, allowList)) continue;
3045
+ const mentionSrc = primaryZoneName === "prose" ? zones.prose : text;
3046
+ const mentionBreaks = primaryZoneName === "prose" ? rawProseMaskBreaks : textBreaks;
3047
+ if (isMetaMentionHit(mentionSrc, start, end, rule, mentionBreaks)) continue;
1455
3048
 
1456
3049
  const { line, col } = offsetToLineCol(text, lineStarts, start, cpPrefix);
1457
3050
  const lineSuppressions = byTargetLine.get(line) || [];
@@ -1464,7 +3057,8 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1464
3057
  }
1465
3058
  if (suppressed) continue;
1466
3059
 
1467
- const sentence = enclosingSentence(text, start, end);
3060
+ const sentence = enclosingSentence(text, start, end, textBreaks);
3061
+ const keepSentence = enclosingSentenceUnclipped(text, start, end);
1468
3062
  const cpStart = cpPrefix ? cpPrefix[start] : start;
1469
3063
  const cpEnd = cpPrefix ? cpPrefix[end] : end;
1470
3064
  findings.push(
@@ -1476,8 +3070,10 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1476
3070
  line,
1477
3071
  col,
1478
3072
  span: { start: cpStart, end: cpEnd },
1479
- match: clipCodepoints(matchedRaw.replace(/\s+/g, " ").trim(), 140),
3073
+ match: cleanMatchExcerpt(matchedRaw, mod, primaryZoneName),
1480
3074
  sentence,
3075
+ keepSentence,
3076
+ registerAdjusted,
1481
3077
  })
1482
3078
  );
1483
3079
  }
@@ -1493,7 +3089,18 @@ export function auditText(text, { filename = "<memory>", modality = null, pack,
1493
3089
  }));
1494
3090
 
1495
3091
  findings.sort((a, b) => (a.line || 0) - (b.line || 0) || (a.col || 0) - (b.col || 0));
1496
- return { findings, unusedSuppressions };
3092
+ const jargonRanges = findings
3093
+ .filter((f) => f.ruleId === "zh-dev-jargon" && f.span)
3094
+ .map((f) => f.span);
3095
+ const filteredFindings = jargonRanges.length > 0
3096
+ ? findings.filter(
3097
+ (f) =>
3098
+ f.ruleId !== "zh-bureaucratic-padding" ||
3099
+ !f.span ||
3100
+ !jargonRanges.some((j) => f.span.start >= j.start - 2 && f.span.end <= j.end + 2)
3101
+ )
3102
+ : findings;
3103
+ return { findings: filteredFindings, unusedSuppressions };
1497
3104
  }
1498
3105
 
1499
3106
  function evaluateSyntheticBinaryFixture(fixture, rule, thresholds) {
@@ -1521,19 +3128,286 @@ function evaluateSyntheticBinaryFixture(fixture, rule, thresholds) {
1521
3128
  return [{ location: `slide ${run}`, match: `${run} consecutive identical slide layouts` }];
1522
3129
  }
1523
3130
  }
3131
+ if (rule.probe === "image-ai-workflow-residue") {
3132
+ if (fixture.startsWith("IMG_WORKFLOW:")) {
3133
+ return [{ location: "metadata", match: fixture.slice("IMG_WORKFLOW:".length), severity: "warning" }];
3134
+ }
3135
+ if (fixture.startsWith("IMG_PROVENANCE:")) {
3136
+ return [{ location: "metadata", match: fixture.slice("IMG_PROVENANCE:".length), severity: "info" }];
3137
+ }
3138
+ }
3139
+ if (rule.probe === "image-ai-palette-slop") {
3140
+ if (fixture.startsWith("IMG_NEON_PALETTE:") || fixture.startsWith("IMG_PLASTIC:")) {
3141
+ return [{ location: "pixels", match: fixture.split(":")[1] || "synthetic-palette" }];
3142
+ }
3143
+ }
3144
+ if (rule.probe === "pdf-visual-layout-slop") {
3145
+ if (
3146
+ fixture.startsWith("PDF_RASTER_DECK:") ||
3147
+ fixture.startsWith("PDF_FLAT_TYPE:") ||
3148
+ fixture.startsWith("PDF_MONOTONY:")
3149
+ ) {
3150
+ return [{ location: "page 1", match: fixture.split(":")[1] || "pdf-layout" }];
3151
+ }
3152
+ }
1524
3153
  return [];
1525
3154
  }
1526
3155
 
1527
- export function makeFinding({ rule, filename, modality, location, line = 1, col = 1, span = null, match, sentence = "" }) {
3156
+ const DELETE_STRATEGY_IDS = new Set([
3157
+ "chatbot-artifact",
3158
+ "markdown-leak",
3159
+ "ui-prompt-echo-badge",
3160
+ "ui-dead-control",
3161
+ "throat-clearing-opener",
3162
+ "closing-platitude",
3163
+ ]);
3164
+
3165
+ const NEED_SOURCE_STRATEGY_IDS = new Set([
3166
+ "unfilled-placeholder",
3167
+ "unsourced-attribution",
3168
+ "unsourced-statistic",
3169
+ "reg-unsubstantiated-superlative",
3170
+ "reg-unqualified-guarantee",
3171
+ ]);
3172
+
3173
+ export function deriveFixStrategy(rule) {
3174
+ if (rule?.fixStrategy) return rule.fixStrategy;
3175
+ const id = String(rule?.id || rule?.ruleId || "").trim();
3176
+ const fam = String(rule?.family || "").trim();
3177
+ if (DELETE_STRATEGY_IDS.has(id) || fam === "hygiene/chat-residue") return "delete";
3178
+ if (
3179
+ NEED_SOURCE_STRATEGY_IDS.has(id) ||
3180
+ fam.startsWith("evidence/") ||
3181
+ fam.startsWith("hygiene/placeholder")
3182
+ ) {
3183
+ return "need-source";
3184
+ }
3185
+ if (
3186
+ id.startsWith("ui-") ||
3187
+ id.startsWith("slide-") ||
3188
+ id.startsWith("pdf-") ||
3189
+ id.startsWith("img-") ||
3190
+ id.startsWith("docx-") ||
3191
+ fam.startsWith("design/") ||
3192
+ fam.startsWith("visual/")
3193
+ ) {
3194
+ return "unwrap-layout";
3195
+ }
3196
+ return "rephrase";
3197
+ }
3198
+
3199
+ const HIGH_CONF_PROBES = new Set([
3200
+ "office-markdown-leak",
3201
+ "ui-dead-control",
3202
+ "slide-word-wall",
3203
+ "slide-bullet-overload",
3204
+ "slide-autofit-shrink",
3205
+ "zh-halfwidth-punctuation",
3206
+ ]);
3207
+ const HIGH_CONF_RULES = new Set(["unfilled-placeholder", "chatbot-artifact", "local-custom-forbid"]);
3208
+ const LOW_CONF_RULES = new Set(["pocket-stealth-vapor", "low-burstiness-vapor"]);
3209
+ const DELETE_KIND_RULES = new Set([
3210
+ "en-throat-clearing-opener",
3211
+ "zh-bureaucratic-padding",
3212
+ "zh-essay-moralizing-ending",
3213
+ "en-essay-moralizing-ending",
3214
+ "chatbot-artifact",
3215
+ ]);
3216
+ const RESTRUCTURE_PROBES = new Set([
3217
+ "staccato-run",
3218
+ "bold-lead-list-wall",
3219
+ "semicolon-tricolon",
3220
+ "rhetorical-qa-cadence",
3221
+ "comma-chain-runon",
3222
+ "narrative-sandwich-frame",
3223
+ "template-skeleton-echo",
3224
+ "low-burstiness-vapor",
3225
+ "slide-word-wall",
3226
+ "slide-bullet-overload",
3227
+ "slide-autofit-shrink",
3228
+ "pptx-layout-monotony",
3229
+ "ui-box-in-box",
3230
+ "ui-pill-soup",
3231
+ "ui-dead-control",
3232
+ ]);
3233
+ const DOCUMENT_SCOPE_PROBES = new Set(["template-skeleton-echo", "low-burstiness-vapor", "em-dash-density"]);
3234
+ const DOCUMENT_SCOPE_RULES = new Set([
3235
+ "pptx-layout-monotony",
3236
+ "low-burstiness-vapor",
3237
+ "template-skeleton-echo",
3238
+ "excessive-em-dash-density",
3239
+ ]);
3240
+ const PARAGRAPH_SCOPE_PROBES = new Set(["bold-lead-list-wall", "narrative-sandwich-frame", "staccato-run"]);
3241
+ const SPAN_SCOPE_RULES = new Set([
3242
+ "unfilled-placeholder",
3243
+ "local-custom-forbid",
3244
+ "zh-halfwidth-punctuation",
3245
+ "en-cliche-lexicon",
3246
+ "reg-unsubstantiated-superlative",
3247
+ ]);
3248
+
3249
+ export function computeFindingConfidence({ ruleId, tier = "taste", severity = "warning", probe = "", registerAdjusted = false }) {
3250
+ if (tier === "invariant" || HIGH_CONF_PROBES.has(probe) || HIGH_CONF_RULES.has(ruleId)) {
3251
+ return "high";
3252
+ }
3253
+ if (severity === "info" || LOW_CONF_RULES.has(ruleId) || registerAdjusted) {
3254
+ return "low";
3255
+ }
3256
+ return "medium";
3257
+ }
3258
+
3259
+ export function buildFindingRevision({
3260
+ ruleId = "",
3261
+ tier = "taste",
3262
+ family = "",
3263
+ probe = "",
3264
+ modality = "markdown",
3265
+ message = null,
3266
+ deletionTest = null,
3267
+ sentence = "",
3268
+ revisionKind = null,
3269
+ revisionScope = null,
3270
+ revisionAvoid = null,
3271
+ fixStrategy = null,
3272
+ }) {
3273
+ let kind = revisionKind || "rewrite";
3274
+ if (!revisionKind) {
3275
+ if (DELETE_KIND_RULES.has(ruleId)) {
3276
+ kind = "delete";
3277
+ } else if (
3278
+ RESTRUCTURE_PROBES.has(probe) ||
3279
+ ruleId === "pocket-stealth-vapor" ||
3280
+ String(family).startsWith("layout/") ||
3281
+ String(family).startsWith("ui/") ||
3282
+ String(family).startsWith("statistics/")
3283
+ ) {
3284
+ kind = "restructure";
3285
+ }
3286
+ }
3287
+
3288
+ let scope = revisionScope || "sentence";
3289
+ if (!revisionScope) {
3290
+ if (DOCUMENT_SCOPE_PROBES.has(probe) || DOCUMENT_SCOPE_RULES.has(ruleId)) {
3291
+ scope = "document";
3292
+ } else if (
3293
+ (modality === "html" || modality === "jsx" || modality === "css" || modality === "svg" || modality === "pptx" || modality === "docx") &&
3294
+ (String(probe).startsWith("ui-") ||
3295
+ String(probe).startsWith("slide-") ||
3296
+ probe === "office-markdown-leak" ||
3297
+ probe === "pptx-layout-monotony" ||
3298
+ ruleId === "ui-prompt-echo-badge" ||
3299
+ ruleId === "markdown-leak")
3300
+ ) {
3301
+ scope = "element";
3302
+ } else if (ruleId === "pocket-stealth-vapor" || PARAGRAPH_SCOPE_PROBES.has(probe)) {
3303
+ scope = "paragraph";
3304
+ } else if (SPAN_SCOPE_RULES.has(ruleId)) {
3305
+ scope = "span";
3306
+ }
3307
+ }
3308
+
3309
+ const effStrategy = fixStrategy || deriveFixStrategy({ id: ruleId, family });
3310
+ let repairTier = "guarded-fix";
3311
+ if (effStrategy === "need-source" || kind === "ask" || DOCUMENT_SCOPE_PROBES.has(probe) || DOCUMENT_SCOPE_RULES.has(ruleId)) {
3312
+ repairTier = "diagnostic-only";
3313
+ } else if (tier === "invariant" && (effStrategy === "delete" || ruleId === "markdown-leak")) {
3314
+ repairTier = "safe-fix";
3315
+ }
3316
+ const doNotAutoEdit = repairTier === "diagnostic-only";
3317
+
3318
+ const instrSrc = deletionTest || message || {};
3319
+ const instruction = {
3320
+ en: String(instrSrc.en || message?.en || ""),
3321
+ zh: String(instrSrc.zh || message?.zh || instrSrc.en || message?.en || ""),
3322
+ };
3323
+
3324
+ const keep = [];
3325
+ if (sentence && modality !== "css") {
3326
+ const seen = new Set();
3327
+ for (const fact of extractProtectedFacts(sentence, { modality, keepMode: true })) {
3328
+ const r = String(fact.raw || "").trim();
3329
+ if (!r || seen.has(r)) continue;
3330
+ seen.add(r);
3331
+ keep.push(r);
3332
+ if (keep.length >= 20) break;
3333
+ }
3334
+ }
3335
+
3336
+ let avoid;
3337
+ if (revisionAvoid && (revisionAvoid.en || revisionAvoid.zh)) {
3338
+ avoid = {
3339
+ en: String(revisionAvoid.en || revisionAvoid.zh || ""),
3340
+ zh: String(revisionAvoid.zh || revisionAvoid.en || ""),
3341
+ };
3342
+ } else if (probe === "negation-pivot" || String(ruleId).includes("negation-pivot")) {
3343
+ avoid = {
3344
+ en: "Do not trade one 'Not X, but Y' slogan for a shorter aphorism or staccato tagline.",
3345
+ zh: "不要把“不是 A,而是 B”的套话置换成另一句短金句或断句口号。",
3346
+ };
3347
+ } else if (kind === "delete") {
3348
+ avoid = {
3349
+ en: "Do not rephrase the filler wrapper; delete it while keeping every concrete number, date, and name in the sentence.",
3350
+ zh: "不要把废话外壳换个说法留着,直接删掉并完整保留句中的数字、时间和实体名。",
3351
+ };
3352
+ } else if (kind === "restructure") {
3353
+ avoid = {
3354
+ en: "Do not compress away concrete facts or invent new numbers while fixing cadence or layout.",
3355
+ zh: "调整结构与节奏时不要删掉具体事实,也不要凭空编造原文没有的数字。",
3356
+ };
3357
+ } else {
3358
+ avoid = {
3359
+ en: "Do not invent unstated numbers, alter inequality bounds, or swap in another cliche phrase.",
3360
+ zh: "改写时不要编造未给出的指标、更改数值边界,或换成另一种高频套话。",
3361
+ };
3362
+ }
3363
+
3364
+ return { kind, scope, repairTier, doNotAutoEdit, instruction, keep, mustPreserve: keep, avoid };
3365
+ }
3366
+
3367
+ export function makeFinding({
3368
+ rule,
3369
+ filename,
3370
+ modality,
3371
+ location,
3372
+ line = 1,
3373
+ col = 1,
3374
+ span = null,
3375
+ match,
3376
+ sentence = "",
3377
+ keepSentence = null,
3378
+ registerAdjusted = false,
3379
+ }) {
1528
3380
  const normMatch = String(match || "").toLowerCase().trim();
1529
3381
  const normSent = String(sentence || normMatch).toLowerCase().replace(/\s+/g, " ").trim();
1530
3382
  const fingerprint = `${rule.id}:${fnv1aHex(`${rule.id}|${normMatch}|${normSent}`)}`;
3383
+ const tier = rule.tier || "taste";
3384
+ const severity = rule.severity || "warning";
3385
+ const family = rule.family || "general";
3386
+ const probe = rule.probe || "";
3387
+ const fixStrategy = deriveFixStrategy(rule);
3388
+ const confidence = computeFindingConfidence({ ruleId: rule.id, tier, severity, probe, registerAdjusted });
3389
+ const revision = buildFindingRevision({
3390
+ ruleId: rule.id,
3391
+ tier,
3392
+ family,
3393
+ probe,
3394
+ modality,
3395
+ message: rule.message,
3396
+ deletionTest: rule.deletionTest || null,
3397
+ sentence: keepSentence !== null && keepSentence !== undefined ? keepSentence : sentence,
3398
+ revisionKind: rule.revisionKind || null,
3399
+ revisionScope: rule.revisionScope || null,
3400
+ revisionAvoid: rule.revisionAvoid || null,
3401
+ fixStrategy,
3402
+ });
1531
3403
  return {
1532
3404
  fingerprint,
1533
3405
  ruleId: rule.id,
1534
- tier: rule.tier || "taste",
1535
- severity: rule.severity || "warning",
1536
- family: rule.family || "general",
3406
+ tier,
3407
+ severity,
3408
+ confidence,
3409
+ fixStrategy,
3410
+ family,
1537
3411
  file: filename,
1538
3412
  modality,
1539
3413
  location,
@@ -1543,6 +3417,7 @@ export function makeFinding({ rule, filename, modality, location, line = 1, col
1543
3417
  match,
1544
3418
  message: rule.message,
1545
3419
  deletionTest: rule.deletionTest || null,
3420
+ revision,
1546
3421
  exemplar: rule.exemplar || null,
1547
3422
  };
1548
3423
  }
@@ -1571,7 +3446,7 @@ function decodeXmlEntities(str) {
1571
3446
  * Audit an already-extracted map of archive entries `{ [entryPath]: string }` for `.docx` or `.pptx`.
1572
3447
  * Shared between Node (`zlib.inflateRawSync`) and Browser (`DecompressionStream('deflate-raw')`).
1573
3448
  */
1574
- export function auditOoxmlEntries(entries, { filename, modality, pack, config = {} }) {
3449
+ export function auditOoxmlEntries(entries, { filename, modality, pack, config = {}, register = null }) {
1575
3450
  const findings = [];
1576
3451
  const skipped = [];
1577
3452
  const rulesById = new Map((pack.rules || []).map((r) => [r.id, r]));
@@ -1599,11 +3474,11 @@ export function auditOoxmlEntries(entries, { filename, modality, pack, config =
1599
3474
  if (!paraText) continue;
1600
3475
  paraIndex += 1;
1601
3476
 
1602
- if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(paraText) || /^#{1,6}\s+\S/.test(paraText))) {
3477
+ if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(paraText) || /^#{1,6}[ \t]+\S/.test(paraText))) {
1603
3478
  findings.push(makeFinding({ rule: mdLeakRule, filename, modality, location: `para ${paraIndex}`, line: paraIndex, match: paraText.slice(0, 100) }));
1604
3479
  }
1605
3480
 
1606
- const sub = auditText(paraText, { filename, modality: "markdown", pack, config });
3481
+ const sub = auditText(paraText, { filename, modality: "markdown", pack, config, register });
1607
3482
  for (const f of sub.findings) {
1608
3483
  if (f.ruleId === "markdown-leak") continue;
1609
3484
  findings.push({ ...f, modality: "docx", location: `para ${paraIndex}`, line: paraIndex });
@@ -1708,7 +3583,7 @@ export function auditOoxmlEntries(entries, { filename, modality, pack, config =
1708
3583
  }
1709
3584
 
1710
3585
  const fullSlideText = slideParagraphs.join("\n");
1711
- if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(fullSlideText) || /^#{1,6}\s+\S/m.test(fullSlideText))) {
3586
+ if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(fullSlideText) || /^#{1,6}[ \t]+\S/m.test(fullSlideText))) {
1712
3587
  findings.push(makeFinding({ rule: mdLeakRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: fullSlideText.slice(0, 90) }));
1713
3588
  }
1714
3589
 
@@ -1771,18 +3646,307 @@ export function auditOoxmlEntries(entries, { filename, modality, pack, config =
1771
3646
  }
1772
3647
  }
1773
3648
 
1774
- // Run text/invariant rules on slide text (hidden slides keep only core error checks)
1775
- const sub = auditText(fullSlideText, { filename, modality: "markdown", pack, config });
3649
+ // Run text/invariant rules on slide text (hidden slides keep only core error checks)
3650
+ const sub = auditText(fullSlideText, { filename, modality: "markdown", pack, config, register });
3651
+ for (const f of sub.findings) {
3652
+ if (isHidden && f.severity !== "error") continue;
3653
+ findings.push({ ...f, modality: "pptx", location: `slide ${slideNum}`, line: slideNum });
3654
+ }
3655
+ });
3656
+
3657
+ return { findings, skipped };
3658
+ }
3659
+
3660
+ return { findings, skipped };
3661
+ }
3662
+
3663
+ /**
3664
+ * Audit parsed PNG/JPEG/WebP metadata & pixel heuristics for AI workflow leaks and template palette/plastic slop.
3665
+ */
3666
+ export function auditImageDocument(parsedImage, { filename, pack, config = {} } = {}) {
3667
+ const findings = [];
3668
+ const skipped = [];
3669
+ if (!parsedImage || !parsedImage.format) {
3670
+ return { findings, skipped: [{ file: filename, reason: "Unparseable image metadata" }] };
3671
+ }
3672
+ const allowList = config?.allow || [];
3673
+ const rulesById = new Map((pack.rules || []).map((r) => [r.id, r]));
3674
+
3675
+ const wfRule = rulesById.get("image-ai-workflow-residue");
3676
+ if (wfRule) {
3677
+ const metaTexts = parsedImage.metadataTexts || [];
3678
+ const workflowMatches = [];
3679
+ const provenanceMatches = [];
3680
+ for (const item of metaTexts) {
3681
+ const key = String(item.key || "").trim();
3682
+ const val = String(item.value || "");
3683
+ const combined = `${key}: ${val}`;
3684
+ if (isAllowedMatch(combined, allowList)) continue;
3685
+ if (
3686
+ /^(?:parameters|prompt|workflow|generation_data)$/i.test(key) ||
3687
+ /(?:Negative prompt:|Steps:\s*\d+\s*,\s*Sampler:|CFG scale:\s*\d|"class_type"\s*:\s*"(?:KSampler|CheckpointLoaderSimple|CLIPTextEncode)")/i.test(val)
3688
+ ) {
3689
+ workflowMatches.push(clipCodepoints(`${key || "chunk"}: ${val.replace(/\s+/g, " ").trim()}`, 120));
3690
+ } else if (
3691
+ /(?:trainedAlgorithmicMedia|c2pa|Midjourney|DALL-E|Adobe Firefly|Stable Diffusion|ComfyUI|AUTOMATIC1111|Flux\.1|Ideogram|Recraft)/i.test(combined)
3692
+ ) {
3693
+ provenanceMatches.push(clipCodepoints(`${key || "tag"}: ${val.replace(/\s+/g, " ").trim()}`, 120));
3694
+ }
3695
+ }
3696
+ if (workflowMatches.length > 0) {
3697
+ findings.push(
3698
+ makeFinding({
3699
+ rule: { ...wfRule, severity: "warning" },
3700
+ filename,
3701
+ modality: "image",
3702
+ location: "metadata",
3703
+ line: 1,
3704
+ match: workflowMatches[0],
3705
+ })
3706
+ );
3707
+ } else if (parsedImage.hasC2pa || provenanceMatches.length > 0) {
3708
+ findings.push(
3709
+ makeFinding({
3710
+ rule: { ...wfRule, severity: "info" },
3711
+ filename,
3712
+ modality: "image",
3713
+ location: "metadata",
3714
+ line: 1,
3715
+ match: provenanceMatches[0] || "C2PA / AI provenance manifest present",
3716
+ })
3717
+ );
3718
+ }
3719
+ }
3720
+
3721
+ const palRule = rulesById.get("image-ai-palette-slop");
3722
+ const pm = parsedImage.pixelMetrics;
3723
+ if (palRule && pm && parsedImage.width >= 64 && parsedImage.height >= 64) {
3724
+ const isNeonPurple =
3725
+ (pm.neonPurpleRatio >= 0.16 && pm.neutralRatio < 0.75) ||
3726
+ (pm.darkBgRatio >= 0.35 && pm.neonPurpleRatio + pm.neonCyanRatio >= 0.14 && pm.neonPurpleRatio >= 0.06);
3727
+ const isPlastic = pm.highSatRatio >= 0.38 && pm.smoothHighSatRatio >= 0.65;
3728
+ if (isNeonPurple || isPlastic) {
3729
+ const reasons = [];
3730
+ if (isNeonPurple) {
3731
+ reasons.push(`neonPurple=${Math.round(pm.neonPurpleRatio * 100)}%`);
3732
+ if (pm.darkBgRatio >= 0.35) reasons.push(`darkBg=${Math.round(pm.darkBgRatio * 100)}%`);
3733
+ }
3734
+ if (isPlastic) {
3735
+ reasons.push(`highSat=${Math.round(pm.highSatRatio * 100)}%`);
3736
+ reasons.push(`smooth=${Math.round(pm.smoothHighSatRatio * 100)}%`);
3737
+ }
3738
+ findings.push(
3739
+ makeFinding({
3740
+ rule: palRule,
3741
+ filename,
3742
+ modality: "image",
3743
+ location: "pixels",
3744
+ line: 1,
3745
+ match: `${parsedImage.width}x${parsedImage.height} (${reasons.join(", ")})`,
3746
+ })
3747
+ );
3748
+ }
3749
+ }
3750
+
3751
+ return { findings, skipped };
3752
+ }
3753
+
3754
+ /**
3755
+ * Audit parsed PDF visual layout, landscape slide density, RGB shading slop, and embedded text artifacts.
3756
+ */
3757
+ export function auditPdfDocument(parsedPdf, { filename, pack, config = {}, register = null } = {}) {
3758
+ const findings = [];
3759
+ const skipped = [];
3760
+ if (!parsedPdf) {
3761
+ return { findings, skipped: [{ file: filename, reason: "Unparseable PDF file" }] };
3762
+ }
3763
+ if (parsedPdf.encrypted) {
3764
+ return { findings, skipped: [{ file: filename, reason: "Encrypted PDF cannot be audited offline" }] };
3765
+ }
3766
+ const pages = parsedPdf.pages || [];
3767
+ if (pages.length === 0) {
3768
+ return { findings, skipped: [{ file: filename, reason: "Missing page objects inside PDF" }] };
3769
+ }
3770
+
3771
+ const rulesById = new Map((pack.rules || []).map((r) => [r.id, r]));
3772
+ const thresholds = pack.thresholds || {};
3773
+ const mdLeakRule = rulesById.get("markdown-leak");
3774
+ const wordWallRule = rulesById.get("slide-word-wall");
3775
+ const gradientRule = rulesById.get("ui-ai-gradient");
3776
+ const pdfLayoutRule = rulesById.get("pdf-visual-layout-slop");
3777
+
3778
+ let rasterOnlyLandscapeCount = 0;
3779
+ let prevSig = null;
3780
+ let monoRun = 0;
3781
+ let monoEmitted = false;
3782
+
3783
+ for (const p of pages) {
3784
+ const pageNum = p.pageNum || 1;
3785
+ const text = p.text || "";
3786
+ const cjkChars = (text.match(/[\u4e00-\u9fff]/gu) || []).length;
3787
+ const latinWords = text.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
3788
+
3789
+ if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(text) || /^#{1,6}[ \t]+\S/m.test(text))) {
3790
+ findings.push(
3791
+ makeFinding({
3792
+ rule: mdLeakRule,
3793
+ filename,
3794
+ modality: "pdf",
3795
+ location: `page ${pageNum}`,
3796
+ line: pageNum,
3797
+ match: clipCodepoints(text.replace(/\s+/g, " ").trim(), 100),
3798
+ })
3799
+ );
3800
+ }
3801
+
3802
+ if (p.isLandscape && wordWallRule) {
3803
+ const maxWords = thresholds.maxSlideWords || 120;
3804
+ const maxZh = thresholds.maxSlideCharsZh || 280;
3805
+ if (latinWords > maxWords || cjkChars > maxZh) {
3806
+ findings.push(
3807
+ makeFinding({
3808
+ rule: wordWallRule,
3809
+ filename,
3810
+ modality: "pdf",
3811
+ location: `page ${pageNum}`,
3812
+ line: pageNum,
3813
+ match: `${latinWords} words / ${cjkChars} CJK chars`,
3814
+ })
3815
+ );
3816
+ }
3817
+ }
3818
+
3819
+ if (gradientRule && Array.isArray(p.rgbColors) && p.rgbColors.length > 0) {
3820
+ const purpleKeys = new Set();
3821
+ for (const rgb of p.rgbColors) {
3822
+ const [h, s] = rgbToHsl(rgb);
3823
+ if (h >= 235 && h <= 345 && s >= 45) {
3824
+ purpleKeys.add(`${Math.floor(rgb[0] / 16)},${Math.floor(rgb[1] / 16)},${Math.floor(rgb[2] / 16)}`);
3825
+ }
3826
+ }
3827
+ if (purpleKeys.size >= 2) {
3828
+ findings.push(
3829
+ makeFinding({
3830
+ rule: gradientRule,
3831
+ filename,
3832
+ modality: "pdf",
3833
+ location: `page ${pageNum}`,
3834
+ line: pageNum,
3835
+ match: `${purpleKeys.size} neon purple-pink RGB fills/shadings`,
3836
+ })
3837
+ );
3838
+ }
3839
+ }
3840
+
3841
+ if (pdfLayoutRule) {
3842
+ if (p.isLandscape && (p.textOpCount || 0) === 0 && (p.imageCount || 0) >= 1) {
3843
+ rasterOnlyLandscapeCount += 1;
3844
+ }
3845
+
3846
+ if (p.isLandscape && (latinWords >= 40 || cjkChars >= 90) && Array.isArray(p.fontSizes) && p.fontSizes.length >= 4) {
3847
+ let minF = p.fontSizes[0];
3848
+ let maxF = p.fontSizes[0];
3849
+ for (let fi = 1; fi < p.fontSizes.length; fi += 1) {
3850
+ const fv = p.fontSizes[fi];
3851
+ if (fv < minF) minF = fv;
3852
+ if (fv > maxF) maxF = fv;
3853
+ }
3854
+ if (minF > 0 && (maxF / minF < 1.2 || (p.width >= 500 && minF < 9.5))) {
3855
+ findings.push(
3856
+ makeFinding({
3857
+ rule: pdfLayoutRule,
3858
+ filename,
3859
+ modality: "pdf",
3860
+ location: `page ${pageNum}`,
3861
+ line: pageNum,
3862
+ match: `font hierarchy collapsed (min=${minF}pt, max=${maxF}pt, words=${latinWords})`,
3863
+ })
3864
+ );
3865
+ }
3866
+ }
3867
+
3868
+ if (pages.length >= 5) {
3869
+ const isPlainTextSlide =
3870
+ p.isLandscape &&
3871
+ (p.imageCount || 0) === 0 &&
3872
+ (latinWords > 8 || cjkChars > 16) &&
3873
+ Array.isArray(p.fontSizes) &&
3874
+ p.fontSizes.length > 0;
3875
+ let pMin = Infinity;
3876
+ let pMax = -Infinity;
3877
+ if (isPlainTextSlide) {
3878
+ for (const fv of p.fontSizes) {
3879
+ if (fv < pMin) pMin = fv;
3880
+ if (fv > pMax) pMax = fv;
3881
+ }
3882
+ }
3883
+ const sig = isPlainTextSlide
3884
+ ? `f:${Math.floor(pMin + 0.5)}-${Math.floor(pMax + 0.5)}|w:${latinWords >= 25 || cjkChars >= 50 ? 2 : 1}`
3885
+ : null;
3886
+ if (sig && sig === prevSig) {
3887
+ monoRun += 1;
3888
+ } else {
3889
+ prevSig = sig;
3890
+ monoRun = sig ? 1 : 0;
3891
+ }
3892
+ if (!monoEmitted && monoRun >= (thresholds.maxIdenticalSlideRun || 4)) {
3893
+ monoEmitted = true;
3894
+ findings.push(
3895
+ makeFinding({
3896
+ rule: pdfLayoutRule,
3897
+ filename,
3898
+ modality: "pdf",
3899
+ location: `page ${pageNum}`,
3900
+ line: pageNum,
3901
+ match: `${monoRun} consecutive identical plain-text landscape PDF pages (${sig})`,
3902
+ })
3903
+ );
3904
+ }
3905
+ }
3906
+ }
3907
+
3908
+ if (text.trim()) {
3909
+ const sub = auditText(text, { filename, modality: "markdown", pack, config, register });
1776
3910
  for (const f of sub.findings) {
1777
- if (isHidden && f.severity !== "error") continue;
1778
- findings.push({ ...f, modality: "pptx", location: `slide ${slideNum}`, line: slideNum });
3911
+ if (f.ruleId === "markdown-leak") continue;
3912
+ findings.push({ ...f, modality: "pdf", location: `page ${pageNum}`, line: pageNum });
1779
3913
  }
1780
- });
3914
+ }
3915
+ }
1781
3916
 
1782
- return { findings, skipped };
3917
+ if (pdfLayoutRule && pages.length >= 2 && rasterOnlyLandscapeCount >= 2) {
3918
+ findings.push(
3919
+ makeFinding({
3920
+ rule: pdfLayoutRule,
3921
+ filename,
3922
+ modality: "pdf",
3923
+ location: "page 1",
3924
+ line: 1,
3925
+ match: `${rasterOnlyLandscapeCount} raster-only landscape pages with zero selectable text`,
3926
+ })
3927
+ );
1783
3928
  }
1784
3929
 
1785
- return { findings, skipped };
3930
+ const coverageWarnings = [];
3931
+ const unreadablePages = [];
3932
+ for (const p of pages) {
3933
+ const emptyText = !(p.text || "").trim();
3934
+ const isRasterSlide = p.isLandscape && (p.textOpCount || 0) === 0 && (p.imageCount || 0) >= 1;
3935
+ if (emptyText && !isRasterSlide && (p.hasFonts || parsedPdf.hasFonts || parsedPdf.hasCompressedStreams || (p.fontSizes?.length || 0) > 0)) {
3936
+ unreadablePages.push(p.pageNum || 1);
3937
+ }
3938
+ }
3939
+ if (unreadablePages.length > 0 && !(rasterOnlyLandscapeCount >= 2 && unreadablePages.length === pages.length)) {
3940
+ coverageWarnings.push({
3941
+ file: filename,
3942
+ code: "unreadable-pdf-text",
3943
+ pages: unreadablePages,
3944
+ message: `PDF contains fonts or streams on page(s) ${unreadablePages.join(", ")} with 0 selectable characters extracted; inspect visually or via pdftotext.`,
3945
+ });
3946
+ }
3947
+
3948
+ findings.sort((a, b) => (a.line || 0) - (b.line || 0) || (a.col || 0) - (b.col || 0));
3949
+ return { findings, skipped, coverageWarnings };
1786
3950
  }
1787
3951
 
1788
3952
  // ---------- Output Formatters (text, json, sarif, github, md) ----------
@@ -1803,8 +3967,181 @@ function escapeGithubData(val) {
1803
3967
  .replace(/\n/g, "%0A");
1804
3968
  }
1805
3969
 
1806
- export function formatReport(report, format = "text", lang = "en") {
1807
- const { findings, checkedCount, skipped = [], unusedSuppressions = [] } = report;
3970
+ export function ruleDocUrl(item, lang = "en") {
3971
+ const ruleId = String(item?.ruleId || item?.id || "");
3972
+ const source = item?.source || "";
3973
+ const packId = item?.packId || "";
3974
+ const isZh = lang === "zh" || ruleId.startsWith("zh-");
3975
+ const base = isZh ? "https://dislop.com/rules/" : "https://dislop.com/en/rules/";
3976
+ if (!ruleId || source === "pattern-library" || packId === "pocket-model") {
3977
+ return base;
3978
+ }
3979
+ return `${base}${ruleId}/`;
3980
+ }
3981
+
3982
+ function cleanAgentText(s, maxLen) {
3983
+ return clipCodepoints(String(s || "").replace(/\s+/g, " ").trim(), maxLen);
3984
+ }
3985
+
3986
+ function localizeSkipReason(reason, lang = "en") {
3987
+ const r = String(reason || "");
3988
+ if (lang !== "zh") return r;
3989
+ const m = r.match(/^Unsupported file extension '(.*)'$/);
3990
+ if (m) return `不支持的文件扩展名 '${m[1]}'`;
3991
+ if (r === "File not found") return "文件不存在";
3992
+ if (r.startsWith("Non-UTF-8 text encoding")) return "非 UTF-8 编码文本,请转换为 UTF-8 后检查";
3993
+ if (r.startsWith("File exceeds 25 MB")) return "文件超过 25 MB 单文件检查上限";
3994
+ if (r === "Missing word/document.xml inside DOCX archive") return "DOCX 归档缺少正文文件 word/document.xml";
3995
+ if (r === "Missing ppt/slides/*.xml inside PPTX archive") return "PPTX 归档缺少幻灯片文件 ppt/slides/*.xml";
3996
+ if (r.startsWith("Uninspectable ")) return `无法解析的文档归档:${r.replace(/^Uninspectable\s+/, "")}`;
3997
+ return r;
3998
+ }
3999
+
4000
+ export function formatAgentReport(report, lang = "en", options = {}) {
4001
+ const { findings = [], checkedCount = 0, skipped = [], unusedSuppressions = [] } = report;
4002
+ const quiet = Boolean(options?.quiet);
4003
+ const failOn = options?.failOn || "error";
4004
+ const minRank = SEVERITY_RANK[failOn] || SEVERITY_RANK.error;
4005
+ const visible = quiet
4006
+ ? findings.filter((f) => (SEVERITY_RANK[f.severity] || 1) >= minRank)
4007
+ : findings;
4008
+
4009
+ if (quiet && visible.length === 0 && unusedSuppressions.length === 0 && skipped.length === 0) {
4010
+ return "";
4011
+ }
4012
+
4013
+ const out = [];
4014
+ const ver = report.version || ENGINE_VERSION;
4015
+ if (visible.length === 0 && unusedSuppressions.length === 0 && skipped.length > 0) {
4016
+ out.push(
4017
+ lang === "zh"
4018
+ ? `dislop ${ver}: 未完成(已检 ${checkedCount} 项、跳过 ${skipped.length} 项)`
4019
+ : `dislop ${ver}: skipped (checked=${checkedCount}, skipped=${skipped.length})`
4020
+ );
4021
+ } else if (visible.length === 0 && unusedSuppressions.length === 0) {
4022
+ if (!quiet) {
4023
+ out.push(
4024
+ lang === "zh"
4025
+ ? `dislop ${ver}: 通过(已检 ${checkedCount} 项、0 处命中)`
4026
+ : `dislop ${ver}: ok (checked=${checkedCount}, findings=0)`
4027
+ );
4028
+ }
4029
+ } else {
4030
+ const errCount = visible.filter((f) => f.severity === "error").length;
4031
+ const warnCount = visible.filter((f) => f.severity === "warning").length;
4032
+ const infoCount = visible.filter((f) => f.severity === "info").length;
4033
+ const reg = report.context?.register || "unspecified";
4034
+ const regSource = report.context?.registerSource || "default";
4035
+
4036
+ if (lang === "zh") {
4037
+ const regZhMap = {
4038
+ unspecified: "未指定",
4039
+ official: "公文",
4040
+ casual: "随笔/口语",
4041
+ argumentative: "议论",
4042
+ technical: "技术文档",
4043
+ marketing: "营销",
4044
+ narrative: "叙事",
4045
+ mixed: "混合",
4046
+ };
4047
+ const srcZhMap = { flag: "参数", frontmatter: "前言", config: "配置", default: "默认", mixed: "多来源" };
4048
+ out.push(
4049
+ `dislop ${ver}: 已检=${checkedCount} 问题=${visible.length}(硬伤=${errCount}、提醒=${warnCount}、提示=${infoCount}) 语体=${regZhMap[reg] || reg}·${srcZhMap[regSource] || regSource}`
4050
+ );
4051
+ } else {
4052
+ out.push(
4053
+ `dislop ${ver}: checked=${checkedCount} findings=${visible.length} (error=${errCount}, warning=${warnCount}, info=${infoCount}) register=${reg}(${regSource})`
4054
+ );
4055
+ }
4056
+
4057
+ const sorted = [...visible].sort((a, b) => {
4058
+ const rDiff = (SEVERITY_RANK[b.severity] || 1) - (SEVERITY_RANK[a.severity] || 1);
4059
+ if (rDiff !== 0) return rDiff;
4060
+ const fa = String(a.file || "");
4061
+ const fb = String(b.file || "");
4062
+ if (fa !== fb) return fa < fb ? -1 : 1;
4063
+ const lDiff = (a.line || 0) - (b.line || 0);
4064
+ if (lDiff !== 0) return lDiff;
4065
+ const cDiff = (a.col || 0) - (b.col || 0);
4066
+ if (cDiff !== 0) return cDiff;
4067
+ const ra = String(a.ruleId || "");
4068
+ const rb = String(b.ruleId || "");
4069
+ return ra === rb ? 0 : ra < rb ? -1 : 1;
4070
+ });
4071
+
4072
+ const AGENT_MAX = 30;
4073
+ const shown = sorted.slice(0, AGENT_MAX);
4074
+ const sevZhMap = { error: "硬伤", warning: "提醒", info: "提示" };
4075
+ const confZhMap = { high: "高", medium: "中", low: "低" };
4076
+ const kindZhMap = { delete: "删减", rewrite: "改写", restructure: "重构" };
4077
+ const scopeZhMap = { span: "片段", sentence: "句级", paragraph: "段级", document: "全文", element: "元素" };
4078
+
4079
+ for (const f of shown) {
4080
+ const rev = f.revision || {};
4081
+ const conf = f.confidence || "medium";
4082
+ const kind = rev.kind || "rewrite";
4083
+ const scope = rev.scope || "sentence";
4084
+ const instrSrc =
4085
+ rev.instruction?.[lang] ||
4086
+ rev.instruction?.en ||
4087
+ f.deletionTest?.[lang] ||
4088
+ f.deletionTest?.en ||
4089
+ f.message?.[lang] ||
4090
+ f.message?.en ||
4091
+ "";
4092
+ const keepArr = Array.isArray(rev.keep) ? rev.keep : [];
4093
+ if (lang === "zh") {
4094
+ const keepPart = keepArr.length > 0 ? ` | 保留=${keepArr.join("、")}` : "";
4095
+ out.push(
4096
+ `[${sevZhMap[f.severity] || f.severity}] ${f.file}:${f.location} ${f.ruleId} 置信=${confZhMap[conf] || conf} ${kindZhMap[kind] || kind}/${scopeZhMap[scope] || scope} | 原文="${cleanAgentText(f.match, 90)}" | 改法="${cleanAgentText(instrSrc, 140)}"${keepPart}`
4097
+ );
4098
+ } else {
4099
+ const keepPart = keepArr.length > 0 ? ` | keep=${keepArr.join(", ")}` : "";
4100
+ out.push(
4101
+ `[${f.severity}] ${f.file}:${f.location} ${f.ruleId} conf=${conf} ${kind}/${scope} | match="${cleanAgentText(f.match, 90)}" | fix="${cleanAgentText(instrSrc, 140)}"${keepPart}`
4102
+ );
4103
+ }
4104
+ }
4105
+
4106
+ if (sorted.length > AGENT_MAX) {
4107
+ const overflow = sorted.length - AGENT_MAX;
4108
+ out.push(
4109
+ lang === "zh"
4110
+ ? `... 另有 ${overflow} 处命中(完整列表请加 --format json)`
4111
+ : `... +${overflow} more findings (use --format json for full list)`
4112
+ );
4113
+ }
4114
+
4115
+ for (const u of unusedSuppressions) {
4116
+ out.push(
4117
+ lang === "zh"
4118
+ ? `[失效豁免] ${u.file}:${u.line} 规则=${u.ruleIds.join(",")}`
4119
+ : `[unused-ignore] ${u.file}:${u.line} rules=${u.ruleIds.join(",")}`
4120
+ );
4121
+ }
4122
+ }
4123
+
4124
+ for (const s of skipped) {
4125
+ const locReason = localizeSkipReason(s.reason, lang);
4126
+ out.push(lang === "zh" ? `[跳过] ${s.file} 原因=${locReason}` : `[skip] ${s.file} reason=${locReason}`);
4127
+ }
4128
+
4129
+ if (!quiet && report.profiles && report.profiles.length > 0) {
4130
+ for (const item of report.profiles) {
4131
+ const p = item.profile;
4132
+ out.push(
4133
+ lang === "zh"
4134
+ ? `[画像] ${item.file} 风险=${p.telemetryRisk.score}/100 句长变异=${p.burstiness.cv} 锚点=${p.concreteness.per100Units}`
4135
+ : `[profile] ${item.file} risk=${p.telemetryRisk.score}/100 cv=${p.burstiness.cv} anchors=${p.concreteness.per100Units}`
4136
+ );
4137
+ }
4138
+ }
4139
+
4140
+ return out.join("\n");
4141
+ }
4142
+
4143
+ export function formatReport(report, format = "text", lang = "en", options = {}) {
4144
+ const { findings, checkedCount, skipped = [], unusedSuppressions = [], coverageWarnings = [], changedFilter = false } = report;
1808
4145
  if (format === "json") {
1809
4146
  return JSON.stringify(report, null, 2);
1810
4147
  }
@@ -1815,7 +4152,7 @@ export function formatReport(report, format = "text", lang = "en") {
1815
4152
  const lines = findings.map((f) => {
1816
4153
  const level = f.severity === "error" ? "error" : f.severity === "warning" ? "warning" : "notice";
1817
4154
  const msg = (f.message?.[lang] || f.message?.en || "").replace(/\r?\n/g, " ");
1818
- return `::${level} file=${escapeGithubProp(f.file)},line=${f.line || 1},col=${f.col || 1},title=${escapeGithubProp(f.ruleId)}::${escapeGithubData(`${msg} (${f.match})`)}`;
4155
+ return `::${level} file=${escapeGithubProp(f.file)},line=${f.line || 1},col=${f.col || 1},title=${escapeGithubProp(f.ruleId)}::${escapeGithubData(`${msg} (${f.match}) — ${ruleDocUrl(f, lang)}`)}`;
1819
4156
  });
1820
4157
  return lines.join("\n");
1821
4158
  }
@@ -1830,41 +4167,162 @@ export function formatReport(report, format = "text", lang = "en") {
1830
4167
  ];
1831
4168
  return rows.join("\n");
1832
4169
  }
4170
+ if (format === "agent") {
4171
+ return formatAgentReport(report, lang, options);
4172
+ }
1833
4173
 
1834
4174
  // Default human text format
4175
+ const quiet = Boolean(options?.quiet);
4176
+ const failOn = options?.failOn || "error";
4177
+ const minRank = SEVERITY_RANK[failOn] || SEVERITY_RANK.error;
4178
+ const visibleFindings = quiet
4179
+ ? findings.filter((f) => (SEVERITY_RANK[f.severity] || 1) >= minRank)
4180
+ : findings;
4181
+
4182
+ if (quiet && visibleFindings.length === 0 && unusedSuppressions.length === 0 && skipped.length === 0 && coverageWarnings.length === 0) {
4183
+ return "";
4184
+ }
4185
+
4186
+ const isReview = report.schema === "dislop.review/1";
1835
4187
  const out = [];
1836
4188
  const skipNote = skipped.length > 0 ? `, ${skipped.length} skipped` : "";
1837
- if (findings.length === 0 && unusedSuppressions.length === 0) {
1838
- out.push(
1839
- lang === "zh"
1840
- ? `dislop: 未发现已知模式(已检 ${checkedCount} 项${skipped.length > 0 ? `,跳过 ${skipped.length} 项` : ""},0 处命中)`
1841
- : `dislop: no known patterns found (${checkedCount} checked${skipNote}, 0 findings)`
1842
- );
4189
+ const zhSkip = skipped.length > 0 ? `,跳过 ${skipped.length} 项` : "";
4190
+ if (changedFilter && checkedCount === 0 && skipped.length === 0 && visibleFindings.length === 0 && coverageWarnings.length === 0) {
4191
+ if (!quiet) {
4192
+ out.push(
4193
+ lang === "zh"
4194
+ ? "dislop: --changed 未匹配到可检查的变更文件(已检 0 项,0 处命中)"
4195
+ : "dislop: --changed matched 0 inspectable files (0 checked, 0 findings)"
4196
+ );
4197
+ }
4198
+ } else if (visibleFindings.length === 0 && unusedSuppressions.length === 0) {
4199
+ if (!quiet) {
4200
+ const fileLabel = checkedCount === 1 ? "1 file" : `${checkedCount} files`;
4201
+ if (isReview) {
4202
+ out.push(
4203
+ lang === "zh"
4204
+ ? `dislop review: 未标出 AI 味问题(已审 ${checkedCount} 项${zhSkip},0 处命中)`
4205
+ : `dislop review: no AI-flavor issues flagged (${fileLabel} reviewed${skipNote}, 0 findings)`
4206
+ );
4207
+ } else {
4208
+ out.push(
4209
+ lang === "zh"
4210
+ ? `dislop: 未发现已知模式(已检 ${checkedCount} 项${zhSkip},0 处命中)`
4211
+ : `dislop: no known patterns found (${fileLabel} checked${skipNote}, 0 findings)`
4212
+ );
4213
+ }
4214
+ }
1843
4215
  } else {
1844
- out.push(`dislop: ${findings.length} finding(s) across ${checkedCount} checked file(s)${skipNote}`);
1845
- for (const f of findings) {
1846
- const msg = f.message?.[lang] || f.message?.en || "";
1847
- out.push(` [${f.severity.toUpperCase()}] ${f.file}:${f.location} ${f.ruleId}`);
1848
- out.push(` match: "${f.match}"`);
1849
- out.push(` why: ${msg}`);
1850
- if (f.deletionTest) {
1851
- out.push(` test: ${f.deletionTest[lang] || f.deletionTest.en}`);
4216
+ const isZh = lang === "zh";
4217
+ const errCount = visibleFindings.filter((f) => f.severity === "error").length;
4218
+ const warnCount = visibleFindings.filter((f) => f.severity === "warning").length;
4219
+ const infoCount = visibleFindings.filter((f) => f.severity === "info").length;
4220
+ if (isZh) {
4221
+ const zhParts = [];
4222
+ if (errCount > 0) zhParts.push(`${errCount} 处硬伤`);
4223
+ if (warnCount > 0) zhParts.push(`${warnCount} 处提醒`);
4224
+ if (infoCount > 0) zhParts.push(`${infoCount} 处提示`);
4225
+ const detail = zhParts.length > 0 ? `(${zhParts.join("、")})` : "";
4226
+ const headNoun =
4227
+ visibleFindings.length > 0
4228
+ ? `发现 ${visibleFindings.length} 处问题${detail}`
4229
+ : `发现 ${unusedSuppressions.length} 处失效豁免`;
4230
+ out.push(`${isReview ? "dislop review" : "dislop"}: ${headNoun},${isReview ? "已审" : "已检"} ${checkedCount} 项${zhSkip}`);
4231
+ } else {
4232
+ const enParts = [];
4233
+ if (errCount > 0) enParts.push(`${errCount} ${errCount === 1 ? "error" : "errors"}`);
4234
+ if (warnCount > 0) enParts.push(`${warnCount} ${warnCount === 1 ? "warning" : "warnings"}`);
4235
+ if (infoCount > 0) enParts.push(`${infoCount} info`);
4236
+ const breakdown = enParts.length > 0 ? ` (${enParts.join(", ")})` : "";
4237
+ const fLabel =
4238
+ visibleFindings.length > 0
4239
+ ? `${visibleFindings.length} ${visibleFindings.length === 1 ? "finding" : "findings"}${breakdown}`
4240
+ : `${unusedSuppressions.length} stale ${unusedSuppressions.length === 1 ? "suppression" : "suppressions"}`;
4241
+ const cLabel = checkedCount === 1 ? "1 file" : `${checkedCount} files`;
4242
+ out.push(`${isReview ? "dislop review" : "dislop"}: ${fLabel} across ${cLabel}${skipNote}`);
4243
+ }
4244
+ const stratLabelsZh = { delete: "删掉", "need-source": "补出处", "unwrap-layout": "去套壳", rephrase: "改写" };
4245
+ const seenRuleIds = new Set();
4246
+ const ruleCounts = new Map();
4247
+ for (const f of visibleFindings) {
4248
+ ruleCounts.set(f.ruleId, (ruleCounts.get(f.ruleId) || 0) + 1);
4249
+ const strat = f.fixStrategy || deriveFixStrategy({ id: f.ruleId, family: f.family });
4250
+ const tag = isZh ? stratLabelsZh[strat] || "改写" : strat;
4251
+ if (isZh) {
4252
+ const sevZh = f.severity === "error" ? "硬伤" : f.severity === "warning" ? "提醒" : "提示";
4253
+ out.push(` [${sevZh}] ${f.file}:${f.location} ${f.ruleId} [${tag}]`);
4254
+ out.push(` 原文: "${f.match}"`);
4255
+ } else {
4256
+ out.push(` [${f.severity.toUpperCase()}] ${f.file}:${f.location} ${f.ruleId} [${tag}]`);
4257
+ out.push(` match: "${f.match}"`);
4258
+ }
4259
+ if (!seenRuleIds.has(f.ruleId)) {
4260
+ seenRuleIds.add(f.ruleId);
4261
+ const msg = f.message?.[lang] || f.message?.en || "";
4262
+ const testTxt = f.deletionTest ? f.deletionTest[lang] || f.deletionTest.en || "" : "";
4263
+ if (msg) {
4264
+ out.push(isZh ? ` 原因: ${msg}` : ` why: ${msg}`);
4265
+ }
4266
+ if (testTxt && testTxt !== msg) {
4267
+ out.push(isZh ? ` 改法: ${testTxt}` : ` fix: ${testTxt}`);
4268
+ }
1852
4269
  }
1853
4270
  }
1854
4271
  for (const u of unusedSuppressions) {
1855
- out.push(` [UNUSED] ${u.file}:${u.line} stale dislop-ignore (${u.ruleIds.join(", ")})`);
4272
+ out.push(
4273
+ isZh
4274
+ ? ` [失效豁免] ${u.file}:${u.line} 未命中的 dislop-ignore (${u.ruleIds.join(", ")})`
4275
+ : ` [UNUSED] ${u.file}:${u.line} stale dislop-ignore (${u.ruleIds.join(", ")})`
4276
+ );
4277
+ }
4278
+ if (visibleFindings.length >= 4 || (checkedCount >= 2 && visibleFindings.length > 0)) {
4279
+ const topStr = Array.from(ruleCounts.entries())
4280
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
4281
+ .slice(0, 5)
4282
+ .map(([rid, cnt]) => `${rid}×${cnt}`)
4283
+ .join(", ");
4284
+ out.push(isZh ? ` 按规则分布: ${topStr}` : ` Top rules: ${topStr}`);
4285
+ out.push(isZh ? " 下一步: 改完可跑 dislop verify --git HEAD <文件>" : " Next: verify edits with dislop verify --git HEAD <file>");
1856
4286
  }
1857
4287
  }
1858
4288
  for (const s of skipped) {
1859
- out.push(` [SKIP] ${s.file} — ${s.reason}`);
4289
+ const locReason = localizeSkipReason(s.reason, lang);
4290
+ out.push(lang === "zh" ? ` [跳过] ${s.file} — ${locReason}` : ` [SKIP] ${s.file} — ${locReason}`);
1860
4291
  }
1861
- if (report.profiles && report.profiles.length > 0) {
4292
+ for (const w of coverageWarnings) {
4293
+ out.push(lang === "zh" ? ` [覆盖提示] ${w.file} — ${w.message}` : ` [COVERAGE] ${w.file} — ${w.message}`);
4294
+ }
4295
+ if (!quiet && report.profiles && report.profiles.length > 0) {
4296
+ const levelZhMap = { low: "低", medium: "中", high: "高" };
4297
+ const statusZhMap = { varied: "有起伏", flat: "偏平", short: "偏短", grounded: "具体", moderate: "一般", vapor: "偏虚", ok: "正常" };
4298
+ const signalZhMap = {
4299
+ "cooccurrence-slop-cluster": "弱套词共现",
4300
+ "semicolon-tricolon": "分号三段排比",
4301
+ "rhetorical-qa-cadence": "自问自答设问",
4302
+ "comma-chain-runon": "多逗号连环句",
4303
+ "narrative-sandwich-frame": "三明治叙事壳",
4304
+ "template-skeleton-echo": "句首骨架复用",
4305
+ "low-burstiness-vapor": "句长齐平空话",
4306
+ "flat-sentence-rhythm": "句长偏平",
4307
+ "zero-concrete-anchors": "缺乏具体锚点",
4308
+ "high-em-dash-density": "破折号过密",
4309
+ };
1862
4310
  for (const item of report.profiles) {
1863
4311
  const p = item.profile;
1864
4312
  const sigs = p.telemetryRisk.signals.length > 0 ? p.telemetryRisk.signals.join(", ") : "none";
1865
- out.push(
1866
- ` [PROFILE] ${item.file} risk=${p.telemetryRisk.score}/100 (${p.telemetryRisk.level}) | burstiness_cv=${p.burstiness.cv} (${p.burstiness.status}) | concreteness=${p.concreteness.per100Units}/100u (${p.concreteness.status}) | mattr=${p.lexical.mattr} | entropy=${p.lexical.charEntropy} | signals=${sigs}`
1867
- );
4313
+ if (lang === "zh") {
4314
+ const sigsZh =
4315
+ p.telemetryRisk.signals.length > 0
4316
+ ? p.telemetryRisk.signals.map((s) => signalZhMap[s] || s).join("、")
4317
+ : "无";
4318
+ out.push(
4319
+ ` [统计] ${item.file} 风险=${p.telemetryRisk.score}/100(${levelZhMap[p.telemetryRisk.level] || p.telemetryRisk.level}) | 句长变异=${p.burstiness.cv}(${statusZhMap[p.burstiness.status] || p.burstiness.status}) | 具体锚点=${p.concreteness.per100Units}/100字(${statusZhMap[p.concreteness.status] || p.concreteness.status}) | 词汇丰富度=${p.lexical.mattr} | 字符熵=${p.lexical.charEntropy} | 信号=${sigsZh}`
4320
+ );
4321
+ } else {
4322
+ out.push(
4323
+ ` [PROFILE] ${item.file} risk=${p.telemetryRisk.score}/100 (${p.telemetryRisk.level}) | burstiness_cv=${p.burstiness.cv} (${p.burstiness.status}) | concreteness=${p.concreteness.per100Units}/100u (${p.concreteness.status}) | mattr=${p.lexical.mattr} | entropy=${p.lexical.charEntropy} | signals=${sigs}`
4324
+ );
4325
+ }
1868
4326
  }
1869
4327
  }
1870
4328
  return out.join("\n");
@@ -1880,7 +4338,7 @@ function buildSarif(report, lang = "en") {
1880
4338
  help: {
1881
4339
  text: f.deletionTest?.[lang] || f.deletionTest?.en || f.message?.en || f.ruleId,
1882
4340
  },
1883
- helpUri: `https://dislop.com/#rule-${f.ruleId}`,
4341
+ helpUri: ruleDocUrl(f, lang),
1884
4342
  defaultConfiguration: {
1885
4343
  level: f.severity === "error" ? "error" : f.severity === "warning" ? "warning" : "note",
1886
4344
  },
@@ -1940,6 +4398,7 @@ export const FAMILY_TO_CATEGORY = {
1940
4398
  "evidence/": "evidence-rigor",
1941
4399
  "deck/": "deck-layout",
1942
4400
  "ui/": "ui-design",
4401
+ "graphic/": "graphic-layout",
1943
4402
  "composite/": "composite-signal",
1944
4403
  };
1945
4404
 
@@ -2006,7 +4465,7 @@ export function buildCatalog(packsById, patternByRuleId = null) {
2006
4465
  message: rule.message || { en: "", zh: "" },
2007
4466
  deletionTest: rule.deletionTest || null,
2008
4467
  exemplar: rule.exemplar || null,
2009
- anchorUrl: `https://dislop.com/#rule-${rule.id}`,
4468
+ anchorUrl: ruleDocUrl({ ruleId: rule.id }, "en"),
2010
4469
  });
2011
4470
  }
2012
4471
  }
@@ -2103,13 +4562,13 @@ export function queryCatalog(entries, filters = {}) {
2103
4562
  // ---------- Zero-Entropy Fact-Lock Ledger (`dislop.fact-ledger/1`) & Stet Spans ----------
2104
4563
 
2105
4564
  const FACT_QUALIFIER_PATTERNS = [
2106
- { group: "max_inc", re: /^(?:up\s+to|no\s+more\s+than|at\s+most|within|max(?:imum)?(?:\s+of)?|<=|≤)\s*/i },
4565
+ { group: "min_inc", re: /^(?:no\s+less\s+than|no\s+fewer\s+than|at\s+least|minimum\s+of|>=|≥)\s*/i },
4566
+ { group: "min_inc", re: /^(?:不低于|不少于|不小于|不得低于|不得少于|至少|最少|最低|起码|下限(?:为)?)\s*/ },
4567
+ { group: "max_inc", re: /^(?:no\s+more\s+than|up\s+to|at\s+most|within|max(?:imum)?(?:\s+of)?|<=|≤)\s*/i },
4568
+ { group: "max_inc", re: /^(?:不超过|不高于|不大于|不多于|不得超过|不得高于|最多|至多|最高|以内|上限(?:为)?)\s*/ },
2107
4569
  { group: "max_lt", re: /^(?:under|below|less\s+than|fewer\s+than|<)\s*/i },
2108
- { group: "max_inc", re: /^(?:最多|不超过|不高于|至多|以内|上限(?:为)?)\s*/ },
2109
4570
  { group: "max_lt", re: /^(?:低于|小于|少于|不到)\s*/ },
2110
- { group: "min_inc", re: /^(?:at\s+least|no\s+less\s+than|no\s+fewer\s+than|minimum\s+of|>=|≥)\s*/i },
2111
4571
  { group: "min_gt", re: /^(?:more\s+than|greater\s+than|over|above|>)\s*/i },
2112
- { group: "min_inc", re: /^(?:至少|不少于|不低于|下限(?:为)?)\s*/ },
2113
4572
  { group: "min_gt", re: /^(?:超过|高于|大于)\s*/ },
2114
4573
  { group: "approx", re: /^(?:approx(?:imately)?\.?|roughly|about|around|~|≈)\s*/i },
2115
4574
  { group: "approx", re: /^(?:约|大约|近)\s*/ },
@@ -2160,6 +4619,24 @@ const UNIT_CANON_MAP = {
2160
4619
  元: "cny",
2161
4620
  };
2162
4621
 
4622
+ function normalizeFactScanText(raw) {
4623
+ let out = "";
4624
+ const s = String(raw || "");
4625
+ for (let i = 0; i < s.length; i += 1) {
4626
+ const code = s.charCodeAt(i);
4627
+ if (code >= 0xff10 && code <= 0xff19) {
4628
+ out += String.fromCharCode(code - 0xff10 + 48);
4629
+ } else if (code === 0xff05) {
4630
+ out += "%";
4631
+ } else if (code === 0x2212) {
4632
+ out += "-";
4633
+ } else {
4634
+ out += s[i];
4635
+ }
4636
+ }
4637
+ return out;
4638
+ }
4639
+
2163
4640
  function canonicalizeNumericToken(token) {
2164
4641
  const clean = token.replace(/,/g, "").trim();
2165
4642
  if (/^[+-]?v\d+(?:\.\d+){1,3}$/i.test(clean)) {
@@ -2183,7 +4660,9 @@ function canonicalizeNumericToken(token) {
2183
4660
  if (!nm) return `${sign}${curr}${rest.toLowerCase()}`;
2184
4661
  const numPart = nm[1];
2185
4662
  const rawUnit = nm[2].trim();
2186
- const normUnit = rawUnit ? UNIT_CANON_MAP[rawUnit.toLowerCase()] || UNIT_CANON_MAP[rawUnit] || rawUnit.toLowerCase() : "";
4663
+ const normUnit = rawUnit
4664
+ ? UNIT_CANON_MAP[rawUnit.toLowerCase()] || UNIT_CANON_MAP[rawUnit] || ZH_UNIT_CANON[rawUnit] || rawUnit.toLowerCase()
4665
+ : "";
2187
4666
  return `${sign}${curr}${numPart}${normUnit}`;
2188
4667
  }
2189
4668
 
@@ -2199,7 +4678,109 @@ function blankMarkupForFactScan(raw, modality) {
2199
4678
  return s;
2200
4679
  }
2201
4680
 
2202
- export function extractProtectedFacts(text, { modality = "markdown" } = {}) {
4681
+ const ZH_NUM_DIGIT = { 零: 0, 〇: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };
4682
+ const ZH_UNIT_CANON = {
4683
+ 个: "个",
4684
+ 条: "条",
4685
+ 项: "项",
4686
+ 次: "次",
4687
+ 份: "份",
4688
+ 页: "页",
4689
+ 行: "行",
4690
+ 人: "人",
4691
+ 家: "家",
4692
+ 位: "人",
4693
+ 名: "人",
4694
+ 台: "台",
4695
+ 套: "套",
4696
+ 批: "批",
4697
+ 种: "种",
4698
+ 轮: "轮",
4699
+ 层: "层",
4700
+ 步: "步",
4701
+ 篇: "篇",
4702
+ 节: "节",
4703
+ 章: "章",
4704
+ };
4705
+
4706
+ function parseChineseNumeral(zhStr) {
4707
+ const s = String(zhStr || "").trim();
4708
+ if (!s) return null;
4709
+ if (s.startsWith("万") || s.startsWith("亿")) return null;
4710
+ if (/^[零〇一二两三四五六七八九]+$/.test(s) && s.length === 1) {
4711
+ return ZH_NUM_DIGIT[s];
4712
+ }
4713
+ let total = 0;
4714
+ let section = 0;
4715
+ let num = 0;
4716
+ for (const ch of s) {
4717
+ if (ch in ZH_NUM_DIGIT) {
4718
+ num = ZH_NUM_DIGIT[ch];
4719
+ } else if (ch === "十") {
4720
+ section += (num === 0 ? 1 : num) * 10;
4721
+ num = 0;
4722
+ } else if (ch === "百") {
4723
+ section += (num === 0 ? 1 : num) * 100;
4724
+ num = 0;
4725
+ } else if (ch === "千") {
4726
+ section += (num === 0 ? 1 : num) * 1000;
4727
+ num = 0;
4728
+ } else if (ch === "万") {
4729
+ if (section + num === 0) return null;
4730
+ total += (section + num) * 10000;
4731
+ section = 0;
4732
+ num = 0;
4733
+ } else if (ch === "亿") {
4734
+ if (section + num === 0) return null;
4735
+ total += (section + num) * 100000000;
4736
+ section = 0;
4737
+ num = 0;
4738
+ } else {
4739
+ return null;
4740
+ }
4741
+ }
4742
+ const val = total + section + num;
4743
+ return val >= 0 ? val : null;
4744
+ }
4745
+
4746
+ function canonicalizeDateToken(rawDate) {
4747
+ const s = String(rawDate || "").trim();
4748
+ let m = s.match(/^((?:19|20)\d{2})[-/.年]\s*(0?[1-9]|1[0-2])[-/.月]\s*(0?[1-9]|[12]\d|3[01])\s*[日号]?$/);
4749
+ if (m) {
4750
+ return `${m[1]}-${String(Number(m[2])).padStart(2, "0")}-${String(Number(m[3])).padStart(2, "0")}`;
4751
+ }
4752
+ m = s.match(/^(0?[1-9]|[12]\d|3[01])[/.](0?[1-9]|[12]\d|3[01])[/.]((?:19|20)\d{2})$/);
4753
+ if (m) {
4754
+ return `${String(Number(m[1])).padStart(2, "0")}/${String(Number(m[2])).padStart(2, "0")}/${m[3]}`;
4755
+ }
4756
+ m = s.match(/^(0?[1-9]|1[0-2])[/.月]\s*(0?[1-9]|[12]\d|3[01])\s*[日号]?$/);
4757
+ if (m) {
4758
+ return `${String(Number(m[1])).padStart(2, "0")}/${String(Number(m[2])).padStart(2, "0")}`;
4759
+ }
4760
+ return s;
4761
+ }
4762
+
4763
+ function extractLeadingQualifier(cleanScan, numStart, lookbackChars = 24) {
4764
+ const lookbehindStart = Math.max(0, numStart - lookbackChars);
4765
+ const prefixWindow = cleanScan.slice(lookbehindStart, numStart);
4766
+ let qualifier = null;
4767
+ let spanStart = numStart;
4768
+ let bestMatchLen = 0;
4769
+ for (const qp of FACT_QUALIFIER_PATTERNS) {
4770
+ for (let offset = 0; offset < prefixWindow.length; offset += 1) {
4771
+ const sub = prefixWindow.slice(offset);
4772
+ const qm = sub.match(qp.re);
4773
+ if (qm && qm[0].length === sub.length && qm[0].length > bestMatchLen) {
4774
+ bestMatchLen = qm[0].length;
4775
+ qualifier = qp.group;
4776
+ spanStart = lookbehindStart + offset;
4777
+ }
4778
+ }
4779
+ }
4780
+ return { qualifier, spanStart };
4781
+ }
4782
+
4783
+ export function extractProtectedFacts(text, { modality = "markdown", keepMode = false } = {}) {
2203
4784
  const raw = String(text || "");
2204
4785
  if (!raw.trim() || modality === "css") return [];
2205
4786
  const lineStarts = buildLineStarts(raw);
@@ -2232,9 +4813,9 @@ export function extractProtectedFacts(text, { modality = "markdown" } = {}) {
2232
4813
  }
2233
4814
 
2234
4815
  // 2. Explicit URLs and real HTML hrefs
2235
- const urlRe = /\bhttps?:\/\/[^\s)>\]"']+/gi;
4816
+ const urlRe = /https?:\/\/[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=%-]+/gi;
2236
4817
  while ((m = urlRe.exec(withoutFences)) !== null) {
2237
- const cleaned = m[0].replace(/[.,;!?。,;!?]+$/, "");
4818
+ const cleaned = m[0].replace(/[.,;!?)]+$/, "");
2238
4819
  claim({
2239
4820
  kind: "url",
2240
4821
  raw: cleaned,
@@ -2259,15 +4840,145 @@ export function extractProtectedFacts(text, { modality = "markdown" } = {}) {
2259
4840
  }
2260
4841
  }
2261
4842
 
2262
- // 3. Numbers, units, versions, and bounding qualifiers in visible prose
2263
- const proseScan = blankMarkupForFactScan(raw, modality);
2264
- const chars = proseScan.split("");
2265
- for (const [s, e] of occupied) {
2266
- for (let i = s; i < e && i < chars.length; i += 1) chars[i] = " ";
4843
+ // 3. Atomic ratios/dates/times and numbers/units/versions in visible prose (1:1 normalized digits/minus)
4844
+ const proseScan = normalizeFactScanText(blankMarkupForFactScan(raw, modality));
4845
+ const maskOccupied = () => {
4846
+ const chars = proseScan.split("");
4847
+ for (const [s, e] of occupied) {
4848
+ for (let i = s; i < e && i < chars.length; i += 1) chars[i] = " ";
4849
+ }
4850
+ return chars.join("");
4851
+ };
4852
+
4853
+ const applyTrailingQual = (scanStr, spanEnd, initialQual) => {
4854
+ if (initialQual) return { qualifier: initialQual, spanEnd };
4855
+ const suffixWindow = scanStr.slice(spanEnd, Math.min(scanStr.length, spanEnd + 6));
4856
+ const suffixList = keepMode
4857
+ ? [{ group: "max_inc", re: /^\s*(?:以内|内|以下|上限)/ }, ...FACT_SUFFIX_QUALIFIERS.slice(1)]
4858
+ : FACT_SUFFIX_QUALIFIERS;
4859
+ for (const sp of suffixList) {
4860
+ const sm = suffixWindow.match(sp.re);
4861
+ if (sm) {
4862
+ return { qualifier: sp.group, spanEnd: spanEnd + sm[0].length };
4863
+ }
4864
+ }
4865
+ return { qualifier: null, spanEnd };
4866
+ };
4867
+
4868
+ if (keepMode) {
4869
+ const cleanKeepDates = maskOccupied();
4870
+ const keepDatePatterns = [
4871
+ /\b\d{4}-\d{1,2}-\d{1,2}(?:[T ]\d{1,2}:\d{2}(?::\d{2})?Z?)?\b/g,
4872
+ /\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{1,2}(?:,\s*\d{4})?\b/gi,
4873
+ /\d{4}\s*年(?:\s*\d{1,2}\s*月(?:\s*\d{1,2}\s*[日号])?)?/g,
4874
+ ];
4875
+ for (const dp of keepDatePatterns) {
4876
+ while ((m = dp.exec(cleanKeepDates)) !== null) {
4877
+ const cleaned = raw.slice(m.index, m.index + m[0].length).trim();
4878
+ claim({
4879
+ kind: "date",
4880
+ raw: cleaned,
4881
+ canonical: cleaned,
4882
+ qualifier: null,
4883
+ span: { start: m.index, end: m.index + m[0].length },
4884
+ });
4885
+ }
4886
+ }
4887
+ }
4888
+
4889
+ // 3a. Atomic ratios (`3:1`, context-ratio `1/2`), dates (`2026-11-23.`, `05/06/2024`, `11/20`, `11月20日`), and clock times (`10:30`)
4890
+ let cleanScan = maskOccupied();
4891
+ const slashRatioRe = /(?<![A-Za-z0-9_.])(\d+)\/(\d+)(?![A-Za-z0-9_./])/g;
4892
+ while ((m = slashRatioRe.exec(cleanScan)) !== null) {
4893
+ const pre = cleanScan.slice(Math.max(0, m.index - 18), m.index);
4894
+ if (/(?:比例|比值|比率|系数|概率|胜率|占比|ratio|fraction|odds|chance)/i.test(pre)) {
4895
+ const { qualifier: preQual, spanStart } = extractLeadingQualifier(cleanScan, m.index);
4896
+ const { qualifier, spanEnd } = applyTrailingQual(cleanScan, m.index + m[0].length, preQual);
4897
+ claim({
4898
+ kind: qualifier ? "qualified-number" : "number",
4899
+ raw: raw.slice(spanStart, spanEnd).trim(),
4900
+ canonical: m[0].trim(),
4901
+ qualifier,
4902
+ span: { start: spanStart, end: spanEnd },
4903
+ });
4904
+ }
4905
+ }
4906
+
4907
+ cleanScan = maskOccupied();
4908
+ const dateTimeRe =
4909
+ /(?:(?<![A-Za-z0-9_.])(?:19|20)\d{2}[-/.年]\s*(?:0?[1-9]|1[0-2])[-/.月]\s*(?:0?[1-9]|[12]\d|3[01])\s*[日号]?(?!(?:\.[0-9]|[A-Za-z0-9_/-]))|(?<![A-Za-z0-9_.])(?:0?[1-9]|[12]\d|3[01])[/.](?:0?[1-9]|[12]\d|3[01])[/.](?:19|20)\d{2}(?!(?:\.[0-9]|[A-Za-z0-9_/-]))|(?<![A-Za-z0-9_.])(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|[12]\d|3[01])(?!(?:\.[0-9]|[A-Za-z0-9_./]))|(?:0?[1-9]|1[0-2])\s*月\s*(?:0?[1-9]|[12]\d|3[01])\s*[日号]|(?<![A-Za-z0-9_:])(?:[01]?\d|2[0-3]):[0-5]\d(?::[0-5]\d)?(?![A-Za-z0-9_:]))/g;
4910
+ while ((m = dateTimeRe.exec(cleanScan)) !== null) {
4911
+ const dtStart = m.index;
4912
+ const dtEnd = m.index + m[0].length;
4913
+ const { qualifier, spanStart } = extractLeadingQualifier(cleanScan, dtStart);
4914
+ const canonical = /:/.test(m[0]) ? m[0].trim() : canonicalizeDateToken(m[0]);
4915
+ claim({
4916
+ kind: "date",
4917
+ raw: raw.slice(spanStart, dtEnd).trim(),
4918
+ canonical,
4919
+ qualifier,
4920
+ span: { start: spanStart, end: dtEnd },
4921
+ });
4922
+ }
4923
+
4924
+ // Non-clock ratios like `3:1` or `16:9`
4925
+ cleanScan = maskOccupied();
4926
+ const colonRatioRe = /(?<![A-Za-z0-9_:])(\d+:\d+)(?![A-Za-z0-9_:])/g;
4927
+ while ((m = colonRatioRe.exec(cleanScan)) !== null) {
4928
+ const { qualifier: preQual, spanStart } = extractLeadingQualifier(cleanScan, m.index);
4929
+ const { qualifier, spanEnd } = applyTrailingQual(cleanScan, m.index + m[0].length, preQual);
4930
+ claim({
4931
+ kind: qualifier ? "qualified-number" : "number",
4932
+ raw: raw.slice(spanStart, spanEnd).trim(),
4933
+ canonical: m[1],
4934
+ qualifier,
4935
+ span: { start: spanStart, end: spanEnd },
4936
+ });
4937
+ }
4938
+
4939
+ // 3b. Constrained Chinese numerals with classifiers / `零`+risk-noun
4940
+ cleanScan = maskOccupied();
4941
+ const zhCountRe =
4942
+ /(?:(?:(共|共计|合计|至少|不超过|不少于|不小于|不高于|不低于|超过|低于|多于|少于|仅|约|大约)\s*)?([一二两三四五六七八九十百千万亿零〇]+)(个月|[个条项次份页行人家位名台套批种轮层步篇章节]))|(?<![0-9])(?:零|0)\s*(误差|漏报|误报|残留|依赖|新增|故障|容忍|阻塞|中断|风险)/g;
4943
+ while ((m = zhCountRe.exec(cleanScan)) !== null) {
4944
+ if (m[2]) {
4945
+ const lead = m[1] || "";
4946
+ const numStr = m[2];
4947
+ const unitStr = m[3];
4948
+ // Require an explicit quantifier when numeral is bare "一" to skip idioms like "一个问题" / "一步到位"
4949
+ if (numStr === "一" && !lead) continue;
4950
+ const val = parseChineseNumeral(numStr);
4951
+ if (val === null) continue;
4952
+ const unitCanon = UNIT_CANON_MAP[unitStr] || ZH_UNIT_CANON[unitStr] || unitStr;
4953
+ const numStart = m.index + (lead ? m[0].indexOf(numStr) : 0);
4954
+ const { qualifier: preQual, spanStart } = extractLeadingQualifier(cleanScan, numStart);
4955
+ const { qualifier, spanEnd } = applyTrailingQual(cleanScan, m.index + m[0].length, preQual);
4956
+ claim({
4957
+ kind: qualifier ? "qualified-number" : "number",
4958
+ raw: raw.slice(spanStart, spanEnd).trim(),
4959
+ canonical: `${val}${unitCanon}`,
4960
+ qualifier,
4961
+ span: { start: spanStart, end: spanEnd },
4962
+ });
4963
+ } else if (m[4]) {
4964
+ const zeroStart = cleanScan.indexOf("0", m.index) === m.index || cleanScan.indexOf("零", m.index) === m.index ? m.index : m.index;
4965
+ const { qualifier: preQual, spanStart } = extractLeadingQualifier(cleanScan, zeroStart);
4966
+ const { qualifier, spanEnd } = applyTrailingQual(cleanScan, m.index + m[0].length, preQual);
4967
+ claim({
4968
+ kind: qualifier ? "qualified-number" : "number",
4969
+ raw: raw.slice(spanStart, spanEnd).trim(),
4970
+ canonical: `0${m[4]}`,
4971
+ qualifier,
4972
+ span: { start: spanStart, end: spanEnd },
4973
+ });
4974
+ }
2267
4975
  }
2268
- const cleanScan = chars.join("");
2269
4976
 
2270
- const numRe = /(?<![A-Za-z0-9_])(?:v\d+(?:\.\d+){1,3}(?![A-Za-z0-9_.])|\d+(?:\.\d+){2,3}(?![A-Za-z0-9_.])|Q[1-4](?![A-Za-z0-9_])|P(?:50|90|95|99)(?![A-Za-z0-9_])|(?:(?<![A-Za-z0-9_.-])[+-])?[$€¥£]\s?\d[\d,]*(?:\.\d+)?(?:\s?[kKmMbB](?![A-Za-z0-9_])|万|亿)?|(?:(?<![A-Za-z0-9_.-])[+-])?\d[\d,]*(?:\.\d+)?(?:\s?(?:%|(?:milliseconds?|ms|minutes?|mins?|seconds?|secs?|s|hours?|hrs?|days?|months?|years?|KB|MB|GB|TB|QPS|TPS|RPS|fps|px|rows?)(?![A-Za-z0-9_])|倍|秒|分钟|小时|天|个月|年|万|亿|元|美元|次|个|条|份|页|行|人|席))?)/g;
4977
+ // 3c. Arabic numbers, units, versions, and bounding qualifiers in visible prose
4978
+ cleanScan = maskOccupied();
4979
+ const numRe = keepMode
4980
+ ? /(?<![A-Za-z0-9_])(?:v\d+(?:\.\d+){1,3}(?![A-Za-z0-9_.])|\d+(?:\.\d+){2,3}(?![A-Za-z0-9_.])|Q[1-4](?![A-Za-z0-9_])|P(?:50|90|95|99)(?![A-Za-z0-9_])|(?:(?<![A-Za-z0-9_.-])[+-])?[$€¥£]\s?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:\s?[kKmMbB](?![A-Za-z0-9_])|万元|亿元|万|亿)?|(?:(?<![A-Za-z0-9_.-])[+-])?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:(?:x|×)(?![A-Za-z0-9_])|\s?(?:%|requests?\/s|req\/s|(?:milliseconds?|ms|microseconds?|us|µs|minutes?|mins?|seconds?|secs?|s|hours?|hrs?|days?|weeks?|months?|years?|KB|MB|GB|TB|PB|QPS|TPS|RPS|fps|px|rows?|items?|files?)(?![A-Za-z0-9_])|毫秒|微秒|秒钟|分钟|小时|个月|万元|亿元|万美元|美元|欧元|日元|千瓦时|倍|秒|天|年|万|亿|元|次|个|条|项|份|页|行|人|家|位|名|台|套|批|种|轮|层|步|篇|章|节))?)/g
4981
+ : /(?<![A-Za-z0-9_])(?:v\d+(?:\.\d+){1,3}(?![A-Za-z0-9_.])|\d+(?:\.\d+){2,3}(?![A-Za-z0-9_.])|Q[1-4](?![A-Za-z0-9_])|P(?:50|90|95|99)(?![A-Za-z0-9_])|(?:(?<![A-Za-z0-9_.-])[+-])?[$€¥£]\s?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:\s?[kKmMbB](?![A-Za-z0-9_])|万|亿)?|(?:(?<![A-Za-z0-9_.-])[+-])?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:\s?(?:%|(?:milliseconds?|ms|minutes?|mins?|seconds?|secs?|s|hours?|hrs?|days?|months?|years?|KB|MB|GB|TB|QPS|TPS|RPS|fps|px|rows?)(?![A-Za-z0-9_])|个月|倍|秒|分钟|小时|天|年|万|亿|元|美元|次|个|条|项|份|页|行|人|家|位|名|台|套|批|种|轮|层|步|篇|章|节))?)/g;
2271
4982
 
2272
4983
  while ((m = numRe.exec(cleanScan)) !== null) {
2273
4984
  const numStart = m.index;
@@ -2282,36 +4993,8 @@ export function extractProtectedFacts(text, { modality = "markdown" } = {}) {
2282
4993
  continue;
2283
4994
  }
2284
4995
 
2285
- const lookbehindStart = Math.max(0, numStart - 24);
2286
- const prefixWindow = cleanScan.slice(lookbehindStart, numStart);
2287
- let qualifier = null;
2288
- let spanStart = numStart;
2289
- let spanEnd = numEnd;
2290
-
2291
- for (const qp of FACT_QUALIFIER_PATTERNS) {
2292
- for (let offset = 0; offset < prefixWindow.length; offset += 1) {
2293
- const sub = prefixWindow.slice(offset);
2294
- const qm = sub.match(qp.re);
2295
- if (qm && qm[0].length === sub.length) {
2296
- qualifier = qp.group;
2297
- spanStart = lookbehindStart + offset;
2298
- break;
2299
- }
2300
- }
2301
- if (qualifier) break;
2302
- }
2303
-
2304
- if (!qualifier) {
2305
- const suffixWindow = cleanScan.slice(numEnd, Math.min(cleanScan.length, numEnd + 6));
2306
- for (const sp of FACT_SUFFIX_QUALIFIERS) {
2307
- const sm = suffixWindow.match(sp.re);
2308
- if (sm) {
2309
- qualifier = sp.group;
2310
- spanEnd = numEnd + sm[0].length;
2311
- break;
2312
- }
2313
- }
2314
- }
4996
+ const { qualifier: preQual, spanStart } = extractLeadingQualifier(cleanScan, numStart);
4997
+ const { qualifier, spanEnd } = applyTrailingQual(cleanScan, numEnd, preQual);
2315
4998
 
2316
4999
  const canonical = canonicalizeNumericToken(token);
2317
5000
 
@@ -2335,15 +5018,18 @@ export function verifyRevision(beforeText, afterText, { modality = "markdown", a
2335
5018
  const preserved = [];
2336
5019
  const missing = [];
2337
5020
  const qualifierDropped = [];
5021
+ const unmatchedIndices = [];
2338
5022
 
2339
- for (const bf of beforeFacts) {
5023
+ // Pass 1: exact (kind-compatible, canonical, qualifier) matches first so bare or mis-ordered tokens cannot steal qualified matches
5024
+ for (let i = 0; i < beforeFacts.length; i += 1) {
5025
+ const bf = beforeFacts[i];
2340
5026
  const isNum = bf.kind === "number" || bf.kind === "qualified-number";
2341
5027
  const matchIdx = pool.findIndex(
2342
5028
  (af) =>
2343
5029
  !af.used &&
2344
5030
  (isNum ? af.kind === "number" || af.kind === "qualified-number" : af.kind === bf.kind) &&
2345
5031
  af.canonical === bf.canonical &&
2346
- (!bf.qualifier || af.qualifier === bf.qualifier)
5032
+ (af.qualifier || null) === (bf.qualifier || null)
2347
5033
  );
2348
5034
  if (matchIdx !== -1) {
2349
5035
  pool[matchIdx].used = true;
@@ -2354,27 +5040,31 @@ export function verifyRevision(beforeText, afterText, { modality = "markdown", a
2354
5040
  canonical: bf.canonical,
2355
5041
  qualifier: bf.qualifier,
2356
5042
  });
2357
- continue;
5043
+ } else {
5044
+ unmatchedIndices.push(i);
2358
5045
  }
5046
+ }
2359
5047
 
2360
- if (bf.qualifier) {
2361
- const bareIdx = pool.findIndex(
2362
- (af) =>
2363
- !af.used &&
2364
- (af.kind === "number" || af.kind === "qualified-number") &&
2365
- af.canonical === bf.canonical
2366
- );
2367
- if (bareIdx !== -1) {
2368
- pool[bareIdx].used = true;
2369
- qualifierDropped.push({
2370
- before: bf.raw,
2371
- after: pool[bareIdx].raw,
2372
- canonical: bf.canonical,
2373
- expectedQualifier: bf.qualifier,
2374
- actualQualifier: pool[bareIdx].qualifier,
2375
- });
2376
- continue;
2377
- }
5048
+ // Pass 2: remaining items catch mismatched, dropped, or newly added qualifiers
5049
+ for (const idx of unmatchedIndices) {
5050
+ const bf = beforeFacts[idx];
5051
+ const isNum = bf.kind === "number" || bf.kind === "qualified-number";
5052
+ const bareIdx = pool.findIndex(
5053
+ (af) =>
5054
+ !af.used &&
5055
+ (isNum ? af.kind === "number" || af.kind === "qualified-number" : af.kind === bf.kind) &&
5056
+ af.canonical === bf.canonical
5057
+ );
5058
+ if (bareIdx !== -1 && (bf.qualifier || pool[bareIdx].qualifier)) {
5059
+ pool[bareIdx].used = true;
5060
+ qualifierDropped.push({
5061
+ before: bf.raw,
5062
+ after: pool[bareIdx].raw,
5063
+ canonical: bf.canonical,
5064
+ expectedQualifier: bf.qualifier,
5065
+ actualQualifier: pool[bareIdx].qualifier,
5066
+ });
5067
+ continue;
2378
5068
  }
2379
5069
 
2380
5070
  missing.push({
@@ -2405,6 +5095,284 @@ export function verifyRevision(beforeText, afterText, { modality = "markdown", a
2405
5095
  };
2406
5096
  }
2407
5097
 
5098
+ export function verifyRevisionBundle(
5099
+ beforeText,
5100
+ afterText,
5101
+ {
5102
+ filename = "<memory>",
5103
+ modality = null,
5104
+ pack = null,
5105
+ config = {},
5106
+ register = null,
5107
+ keepTerms = [],
5108
+ allowAdded = false,
5109
+ strict = false,
5110
+ } = {}
5111
+ ) {
5112
+ const bef = String(beforeText || "");
5113
+ const aft = String(afterText || "");
5114
+ const mod = modality || detectModality(filename) || "markdown";
5115
+ const regInfo = resolveRegister(bef, { filename, flagRegister: register, config });
5116
+ const effRegister = regInfo.register;
5117
+ const factLedger = verifyRevision(bef, aft, { allowAdded });
5118
+
5119
+ const requested = [];
5120
+ const seenKeep = new Set();
5121
+ for (const t of Array.isArray(keepTerms) ? keepTerms : []) {
5122
+ const clean = String(t || "").trim();
5123
+ if (!clean || seenKeep.has(clean)) continue;
5124
+ seenKeep.add(clean);
5125
+ requested.push(clean);
5126
+ }
5127
+ const aftLower = aft.toLowerCase();
5128
+ const kept = [];
5129
+ const missing = [];
5130
+ for (const term of requested) {
5131
+ const isAscii = /^[A-Za-z0-9 _.-]+$/.test(term);
5132
+ const present = isAscii ? aftLower.includes(term.toLowerCase()) : aft.includes(term);
5133
+ if (present) kept.push(term);
5134
+ else missing.push(term);
5135
+ }
5136
+ const keepTermsCheck = { requested, kept, missing };
5137
+
5138
+ let findingsDelta = null;
5139
+ if (pack) {
5140
+ const beforeRes = auditText(bef, { filename, modality: mod, pack, config, register: effRegister });
5141
+ const afterRes = auditText(aft, { filename, modality: mod, pack, config, register: effRegister });
5142
+ const beforeCounts = new Map();
5143
+ const afterCounts = new Map();
5144
+ const findingKey = (f) => `${f.ruleId}|${f.match || ""}`;
5145
+ for (const f of beforeRes.findings) {
5146
+ const k = findingKey(f);
5147
+ beforeCounts.set(k, (beforeCounts.get(k) || 0) + 1);
5148
+ }
5149
+ for (const f of afterRes.findings) {
5150
+ const k = findingKey(f);
5151
+ afterCounts.set(k, (afterCounts.get(k) || 0) + 1);
5152
+ }
5153
+ let resolvedCount = 0;
5154
+ for (const [k, bc] of beforeCounts.entries()) {
5155
+ const ac = afterCounts.get(k) || 0;
5156
+ if (bc > ac) resolvedCount += bc - ac;
5157
+ }
5158
+ const seenAfter = new Map();
5159
+ const introduced = [];
5160
+ for (const f of afterRes.findings) {
5161
+ const k = findingKey(f);
5162
+ const nth = (seenAfter.get(k) || 0) + 1;
5163
+ seenAfter.set(k, nth);
5164
+ if (nth > (beforeCounts.get(k) || 0)) {
5165
+ introduced.push({
5166
+ ruleId: f.ruleId,
5167
+ severity: f.severity,
5168
+ fixStrategy: f.fixStrategy,
5169
+ line: f.line,
5170
+ col: f.col,
5171
+ match: f.match,
5172
+ });
5173
+ }
5174
+ }
5175
+ findingsDelta = {
5176
+ beforeCount: beforeRes.findings.length,
5177
+ afterCount: afterRes.findings.length,
5178
+ resolvedCount,
5179
+ introduced,
5180
+ introducedErrors: introduced.filter((x) => x.severity === "error").length,
5181
+ };
5182
+ }
5183
+
5184
+ const beforeChars = codePointLength(bef.trim());
5185
+ const afterChars = codePointLength(aft.trim());
5186
+ const ratio = beforeChars === 0 ? 1 : Number((afterChars / beforeChars).toFixed(4));
5187
+ let lengthStatus = "ok";
5188
+ if (beforeChars >= 120 && ratio < 0.5) {
5189
+ lengthStatus = "over-compressed";
5190
+ } else if (beforeChars >= 60 && beforeChars <= 160 && ratio > 1.8) {
5191
+ lengthStatus = "over-expanded";
5192
+ }
5193
+ const lengthCheck = {
5194
+ beforeChars,
5195
+ afterChars,
5196
+ ratio,
5197
+ status: lengthStatus,
5198
+ };
5199
+
5200
+ // Built-in anti-degradation guardrails: protect author voice, cadence, information density, and modality precision
5201
+ const beforeProf = analyzeTextProfile(bef, { modality: mod, config });
5202
+ const afterProf = analyzeTextProfile(aft, { modality: mod, config });
5203
+ const degWarnings = [];
5204
+
5205
+ const countPersp = (s) =>
5206
+ (s.match(/(?:我|我们|咱们|你|你们)/g) || []).length +
5207
+ (s.match(/\b(?:I|we|my|our|you|your)\b/gi) || []).length;
5208
+ const beforePersp = countPersp(bef);
5209
+ const afterPersp = countPersp(aft);
5210
+ const perspectivePreserved = !(beforePersp >= 2 && afterPersp === 0);
5211
+ if (!perspectivePreserved) {
5212
+ degWarnings.push({
5213
+ code: "voice-perspective-erased",
5214
+ severity: "warning",
5215
+ message: {
5216
+ en: "Original author perspective (first/second person) was erased into impersonal prose.",
5217
+ zh: "原文的第一/第二人称作者视角被完全抹平,改成了冰冷的第三方腔。",
5218
+ },
5219
+ });
5220
+ }
5221
+
5222
+ if (
5223
+ effRegister !== "technical" &&
5224
+ effRegister !== "official" &&
5225
+ beforeProf.sentenceCount >= 4 &&
5226
+ afterProf.sentenceCount >= 4 &&
5227
+ beforeProf.burstiness.cv >= 0.32 &&
5228
+ afterProf.burstiness.cv < 0.22 &&
5229
+ beforeProf.burstiness.cv - afterProf.burstiness.cv >= 0.12
5230
+ ) {
5231
+ degWarnings.push({
5232
+ code: "cadence-flattened",
5233
+ severity: "warning",
5234
+ message: {
5235
+ en: "Sentence rhythm was flattened into uniform cadence, losing the original phrasing variation.",
5236
+ zh: "原文错落的句长节奏被压平变呆板,丢失了自然的表达起伏。",
5237
+ },
5238
+ });
5239
+ }
5240
+
5241
+ const CASUAL_MARKER_RE = /(?:自己收|只出|咱们|大伙|顺手|包邮|私聊|闲置|\b(?:folks|gonna|wanna|my own)\b)/gi;
5242
+ const STIFF_BOOKISH_RE = /(?:旨在|谨此|兹有|切勿|务必|仅出|略有|偶见|赋能|抓手|闭环|\b(?:thereof|herein|pursuant to|endeavor to|facilitate)\b)/gi;
5243
+ const SLANG_DRIFT_RE = /(?:家人们|绝绝子|咱就是说|尊嘟假嘟|\b(?:no cap|frfr|lowkey)\b)/gi;
5244
+ const befCasualHits = (bef.match(CASUAL_MARKER_RE) || []).length;
5245
+ const befStiffSet = new Set((bef.match(STIFF_BOOKISH_RE) || []).map((x) => x.toLowerCase()));
5246
+ const aftNewStiff = (aft.match(STIFF_BOOKISH_RE) || []).filter((x) => !befStiffSet.has(x.toLowerCase()));
5247
+ const isCasualRegister = effRegister === "casual" || (befCasualHits >= 2 && befStiffSet.size === 0);
5248
+ if (isCasualRegister && aftNewStiff.length >= 2) {
5249
+ degWarnings.push({
5250
+ code: "register-drift",
5251
+ severity: "warning",
5252
+ message: {
5253
+ en: "Conversational wording drifted into stiff bookish/bureaucratic prose instead of keeping the original casual voice.",
5254
+ zh: "口语/个人表达被改写成生硬书面或公文腔,丢掉了原本的自然口吻。",
5255
+ },
5256
+ });
5257
+ } else if (
5258
+ (effRegister === "official" || effRegister === "technical" || pack?.id === "regulated-comms" || pack?.id === "engineering-spec") &&
5259
+ !SLANG_DRIFT_RE.test(bef)
5260
+ ) {
5261
+ SLANG_DRIFT_RE.lastIndex = 0;
5262
+ if (SLANG_DRIFT_RE.test(aft)) {
5263
+ degWarnings.push({
5264
+ code: "register-drift",
5265
+ severity: "warning",
5266
+ message: {
5267
+ en: "Formal/technical draft drifted into fake-casual internet slang.",
5268
+ zh: "正式或技术文本中混入了轻浮网络口水词,与当前写作场景不符。",
5269
+ },
5270
+ });
5271
+ }
5272
+ }
5273
+
5274
+ if (
5275
+ beforeProf.concreteness.anchorCount >= 3 &&
5276
+ afterProf.concreteness.anchorCount < beforeProf.concreteness.anchorCount * 0.7
5277
+ ) {
5278
+ degWarnings.push({
5279
+ code: "information-loss",
5280
+ severity: "warning",
5281
+ message: {
5282
+ en: "Concrete facts, metrics, paths, or examples dropped by >30%, reducing information density.",
5283
+ zh: "具体数字、路径、时间或实例锚点流失超过 30%,信息量受损。",
5284
+ },
5285
+ });
5286
+ }
5287
+
5288
+ const modalityBuckets = [
5289
+ ["estimate", /(?:预计|约|大约|估算|大概|\b(?:projected|estimated|approx(?:imately)?|roughly|target)\b)/i],
5290
+ ["condition", /(?:仅在|除非|前提是|当且仅当|\b(?:only when|unless|provided that|if and only if)\b)/i],
5291
+ ["unverified", /(?:暂未|尚未|待确认|待验证|\b(?:pending|unverified|not yet)\b)/i],
5292
+ ["measured", /(?:实测|压测|基准测试|\b(?:measured|benchmarked|observed)\b)/i],
5293
+ ];
5294
+ const modalityDrifts = [];
5295
+ for (const [bName, bRe] of modalityBuckets) {
5296
+ if (bRe.test(bef) && !bRe.test(aft)) {
5297
+ modalityDrifts.push(bName);
5298
+ }
5299
+ }
5300
+ if (modalityDrifts.length > 0) {
5301
+ const joinedDrifts = modalityDrifts.join(", ");
5302
+ degWarnings.push({
5303
+ code: "modality-drifted",
5304
+ severity: "error",
5305
+ message: {
5306
+ en: `Precision/modality qualifiers dropped (${joinedDrifts}); revision may overclaim or lose scope bounds.`,
5307
+ zh: `边界或模态限定词丢失(${joinedDrifts}),改稿可能导致表述失准或过度承诺。`,
5308
+ },
5309
+ });
5310
+ }
5311
+
5312
+ if (findingsDelta && findingsDelta.introduced.length > 0) {
5313
+ degWarnings.push({
5314
+ code: "secondary-slop-introduced",
5315
+ severity: findingsDelta.introducedErrors > 0 ? "error" : "warning",
5316
+ message: {
5317
+ en: "Revision introduced new AI-slop pattern(s) not present in the original.",
5318
+ zh: "改稿新引入了原文原本没有的 AI 套路或残留问题。",
5319
+ },
5320
+ });
5321
+ }
5322
+
5323
+ if (lengthStatus === "over-compressed") {
5324
+ degWarnings.push({
5325
+ code: "over-compressed",
5326
+ severity: "warning",
5327
+ message: {
5328
+ en: "Revision shrank below 50% of original length; verify no substance or nuance was stripped.",
5329
+ zh: "改稿篇幅被压缩至原文 50% 以下,请核对是否误删干货或细节。",
5330
+ },
5331
+ });
5332
+ } else if (lengthStatus === "over-expanded") {
5333
+ degWarnings.push({
5334
+ code: "over-expanded",
5335
+ severity: "warning",
5336
+ message: {
5337
+ en: "Short UI/label copy expanded above 180% of original length; check layout overflow risk.",
5338
+ zh: "短文案被扩写超过原文 180%,注意检查界面换行或卡片溢出。",
5339
+ },
5340
+ });
5341
+ }
5342
+
5343
+ const antiDegradation = {
5344
+ status: degWarnings.length === 0 ? "preserved" : "degraded",
5345
+ warnings: degWarnings,
5346
+ metrics: {
5347
+ beforeCv: beforeProf.burstiness.cv,
5348
+ afterCv: afterProf.burstiness.cv,
5349
+ beforeAnchors: beforeProf.concreteness.anchorCount,
5350
+ afterAnchors: afterProf.concreteness.anchorCount,
5351
+ perspectivePreserved,
5352
+ modalityDrifts,
5353
+ secondarySlopCount: findingsDelta ? findingsDelta.introduced.length : 0,
5354
+ },
5355
+ };
5356
+
5357
+ const hardPass =
5358
+ factLedger.status === "preserved" &&
5359
+ keepTermsCheck.missing.length === 0 &&
5360
+ modalityDrifts.length === 0 &&
5361
+ (findingsDelta ? findingsDelta.introducedErrors === 0 : true);
5362
+ const ok = hardPass && (!strict || degWarnings.length === 0);
5363
+
5364
+ return {
5365
+ schema: "dislop.verify/1",
5366
+ ok,
5367
+ status: ok ? "passed" : "failed",
5368
+ factLedger,
5369
+ keepTerms: keepTermsCheck,
5370
+ lengthCheck,
5371
+ antiDegradation,
5372
+ ...(findingsDelta ? { findingsDelta } : {}),
5373
+ };
5374
+ }
5375
+
2408
5376
  // ---------- Offline Deterministic Voice Profile (`dislop.voice/1`) ----------
2409
5377
 
2410
5378
  function roundHalfUp1(v) {