dislop 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/plugins/marketplace.json +20 -0
- package/.claude-plugin/marketplace.json +33 -0
- package/.claude-plugin/plugin.json +23 -0
- package/.codex-plugin/plugin.json +49 -0
- package/.cursor-plugin/plugin.json +27 -0
- package/.mcp.json +8 -0
- package/.pre-commit-hooks.yaml +13 -0
- package/LICENSE +202 -0
- package/PRODUCT.md +49 -0
- package/README.md +245 -2
- package/README.zh-CN.md +242 -0
- package/action.yml +90 -0
- package/assets/logo.svg +8 -0
- package/bin/dislop-mcp.mjs +5 -0
- package/bin/dislop.mjs +1967 -0
- package/gemini-extension.json +10 -0
- package/mcp.json +9 -0
- package/models/manifest.json +90 -0
- package/models/pocket-slop-v1.json +1 -0
- package/package.json +92 -4
- package/packs/business-brief/pack.json +598 -0
- package/packs/core/pack.json +198 -0
- package/packs/deck-and-ui/pack.json +290 -0
- package/packs/engineering-spec/pack.json +144 -0
- package/packs/executive-deck/pack.json +98 -0
- package/packs/literary-essay/pack.json +324 -0
- package/packs/regulated-comms/pack.json +99 -0
- package/patterns/README.md +39 -0
- package/patterns/banks/composite-fusion.json +36 -0
- package/patterns/banks/discourse-rhythm.json +95 -0
- package/patterns/banks/lexical-signals.json +74 -0
- package/patterns/banks/syntactic-frames.json +45 -0
- package/patterns/banks/visual-deck.json +37 -0
- package/patterns/dimensions/artifacts.json +121 -0
- package/patterns/dimensions/discourse.json +412 -0
- package/patterns/dimensions/lexical.json +172 -0
- package/patterns/dimensions/rhythm.json +206 -0
- package/patterns/dimensions/syntactic.json +285 -0
- package/patterns/dimensions/visual-and-deck.json +322 -0
- package/patterns/taxonomy.json +112 -0
- package/plugin.json +41 -0
- package/server.json +18 -0
- package/skills/dislop/SKILL.md +58 -0
- package/skills/dislop/agents/openai.yaml +6 -0
- package/skills/dislop/references/business-and-rfc.md +26 -0
- package/skills/dislop/references/editorial-and-essay.md +20 -0
- package/skills/dislop/references/regulated-and-precision.md +27 -0
- package/skills/dislop/references/web-ui-and-deck.md +26 -0
- package/src/binary-node.mjs +85 -0
- package/src/core.mjs +2500 -0
- package/src/local-model.mjs +977 -0
- package/src/pattern-engine.mjs +853 -0
- package/src/pocket-model.mjs +707 -0
package/src/core.mjs
ADDED
|
@@ -0,0 +1,2500 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dislop core engine (zero Node.js or DOM globals).
|
|
3
|
+
* Shared identically by Node CLI, Node MCP server, and Browser Workbench (`site/`).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const ENGINE_VERSION = "0.7.0";
|
|
7
|
+
|
|
8
|
+
export const SEVERITY_RANK = {
|
|
9
|
+
info: 1,
|
|
10
|
+
warning: 2,
|
|
11
|
+
error: 3,
|
|
12
|
+
never: 99,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const EXT_TO_MODALITY = {
|
|
16
|
+
".md": "markdown",
|
|
17
|
+
".mdx": "markdown",
|
|
18
|
+
".txt": "text",
|
|
19
|
+
".html": "html",
|
|
20
|
+
".htm": "html",
|
|
21
|
+
".css": "css",
|
|
22
|
+
".jsx": "jsx",
|
|
23
|
+
".tsx": "jsx",
|
|
24
|
+
".svg": "svg",
|
|
25
|
+
".docx": "docx",
|
|
26
|
+
".pptx": "pptx",
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export function detectModality(filename = "") {
|
|
30
|
+
if (!filename || filename === "<memory>") return "markdown";
|
|
31
|
+
const base = String(filename).split(/[\\/]/).pop().toLowerCase();
|
|
32
|
+
const dot = base.lastIndexOf(".");
|
|
33
|
+
if (dot <= 0) return null;
|
|
34
|
+
return EXT_TO_MODALITY[base.slice(dot)] || null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function defaultPackForModality(modality) {
|
|
38
|
+
if (modality === "html" || modality === "css" || modality === "jsx" || modality === "svg" || modality === "pptx") {
|
|
39
|
+
return "deck-and-ui";
|
|
40
|
+
}
|
|
41
|
+
return "business-brief";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function resolveEffectivePack(packId, packsById, config = {}) {
|
|
45
|
+
const target = packsById[packId];
|
|
46
|
+
if (!target) {
|
|
47
|
+
const available = Object.keys(packsById).sort().join(", ");
|
|
48
|
+
throw new Error(`Unknown Taste Pack '${packId}'. Available packs: ${available}`);
|
|
49
|
+
}
|
|
50
|
+
const chain = [];
|
|
51
|
+
const visited = new Set();
|
|
52
|
+
function collect(id) {
|
|
53
|
+
if (visited.has(id)) return;
|
|
54
|
+
visited.add(id);
|
|
55
|
+
const p = packsById[id];
|
|
56
|
+
if (!p) return;
|
|
57
|
+
for (const parentId of p.extends || []) {
|
|
58
|
+
collect(parentId);
|
|
59
|
+
}
|
|
60
|
+
chain.push(p);
|
|
61
|
+
}
|
|
62
|
+
collect(packId);
|
|
63
|
+
|
|
64
|
+
const mergedThresholds = {};
|
|
65
|
+
const rulesById = new Map();
|
|
66
|
+
for (const p of chain) {
|
|
67
|
+
Object.assign(mergedThresholds, p.thresholds || {});
|
|
68
|
+
for (const rule of p.rules || []) {
|
|
69
|
+
const override = config?.rules?.[rule.id];
|
|
70
|
+
if (override === "off" && rule.tier !== "invariant") {
|
|
71
|
+
rulesById.delete(rule.id);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const effectiveRule = { ...rule };
|
|
75
|
+
if (typeof override === "string" && SEVERITY_RANK[override] && rule.tier !== "invariant") {
|
|
76
|
+
effectiveRule.severity = override;
|
|
77
|
+
}
|
|
78
|
+
rulesById.set(rule.id, effectiveRule);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (Array.isArray(config?.forbid) && config.forbid.length > 0) {
|
|
83
|
+
rulesById.set("local-custom-forbid", {
|
|
84
|
+
id: "local-custom-forbid",
|
|
85
|
+
tier: "invariant",
|
|
86
|
+
severity: "error",
|
|
87
|
+
family: "hygiene/forbid",
|
|
88
|
+
probe: "regex",
|
|
89
|
+
zones: ["raw"],
|
|
90
|
+
modalities: ["markdown", "text", "html", "css", "jsx", "svg", "docx", "pptx", "pdf"],
|
|
91
|
+
patterns: config.forbid,
|
|
92
|
+
message: {
|
|
93
|
+
en: "Matched forbidden pattern from local `.dislop.local.json` policy.",
|
|
94
|
+
zh: "命中本地 `.dislop.local.json` 私有禁止词规则。",
|
|
95
|
+
},
|
|
96
|
+
deletionTest: {
|
|
97
|
+
en: "Remove or de-identify the forbidden private term before committing.",
|
|
98
|
+
zh: "提交前删除或脱敏该私有敏感词。",
|
|
99
|
+
},
|
|
100
|
+
exemplar: null,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
...target,
|
|
106
|
+
thresholds: mergedThresholds,
|
|
107
|
+
rules: Array.from(rulesById.values()),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const UTF8_ENCODER = new TextEncoder();
|
|
112
|
+
|
|
113
|
+
export function fnv1aHex(input) {
|
|
114
|
+
const bytes = UTF8_ENCODER.encode(input);
|
|
115
|
+
let hash = 0x811c9dc5;
|
|
116
|
+
for (let i = 0; i < bytes.length; i += 1) {
|
|
117
|
+
hash ^= bytes[i];
|
|
118
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
119
|
+
}
|
|
120
|
+
return hash.toString(16).padStart(8, "0");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function preserveLinesBlank(segment) {
|
|
124
|
+
return segment.replace(/[^\r\n]/g, " ");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function buildLineStarts(text) {
|
|
128
|
+
const starts = [0];
|
|
129
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
130
|
+
if (text.charCodeAt(i) === 10) {
|
|
131
|
+
starts.push(i + 1);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return starts;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function offsetToLineCol(text, lineStarts, offset, cpPrefix = null) {
|
|
138
|
+
let lo = 0;
|
|
139
|
+
let hi = lineStarts.length - 1;
|
|
140
|
+
while (lo <= hi) {
|
|
141
|
+
const mid = (lo + hi) >> 1;
|
|
142
|
+
if (lineStarts[mid] <= offset) {
|
|
143
|
+
lo = mid + 1;
|
|
144
|
+
} else {
|
|
145
|
+
hi = mid - 1;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const lineIdx = Math.max(0, hi);
|
|
149
|
+
const lineStart = lineStarts[lineIdx];
|
|
150
|
+
// Unified Unicode codepoint column (1-based) so Node, Browser, and Python agree on emoji/CJK
|
|
151
|
+
const col = cpPrefix
|
|
152
|
+
? cpPrefix[offset] - cpPrefix[lineStart] + 1
|
|
153
|
+
: Array.from(text.slice(lineStart, offset)).length + 1;
|
|
154
|
+
return { line: lineIdx + 1, col };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function buildCodePointPrefix(text) {
|
|
158
|
+
const prefix = new Int32Array(text.length + 1);
|
|
159
|
+
let cp = 0;
|
|
160
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
161
|
+
prefix[i] = cp;
|
|
162
|
+
const c = text.charCodeAt(i);
|
|
163
|
+
if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length) {
|
|
164
|
+
const c2 = text.charCodeAt(i + 1);
|
|
165
|
+
if (c2 >= 0xdc00 && c2 <= 0xdfff) {
|
|
166
|
+
i += 1;
|
|
167
|
+
prefix[i] = cp;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
cp += 1;
|
|
171
|
+
}
|
|
172
|
+
prefix[text.length] = cp;
|
|
173
|
+
return prefix;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function isSentenceBreakAt(text, idx) {
|
|
177
|
+
const ch = text[idx];
|
|
178
|
+
if (!ch || !/[\n.!?。!?]/.test(ch)) return false;
|
|
179
|
+
if (ch !== ".") return true;
|
|
180
|
+
const prev = idx > 0 ? text[idx - 1] : "";
|
|
181
|
+
const next = idx + 1 < text.length ? text[idx + 1] : "";
|
|
182
|
+
if (/\d/.test(prev) && /\d/.test(next)) return false;
|
|
183
|
+
const beforeWord = text.slice(Math.max(0, idx - 6), idx);
|
|
184
|
+
if (/(?:^|\s)(?:vs|v|approx|e\.g|i\.e)$/i.test(beforeWord)) return false;
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function enclosingSentence(text, start, end) {
|
|
189
|
+
let left = start;
|
|
190
|
+
while (left > 0 && !isSentenceBreakAt(text, left - 1)) {
|
|
191
|
+
left -= 1;
|
|
192
|
+
}
|
|
193
|
+
let right = end;
|
|
194
|
+
while (right < text.length && !isSentenceBreakAt(text, right)) {
|
|
195
|
+
right += 1;
|
|
196
|
+
}
|
|
197
|
+
if (right < text.length && /[.!?。!?]/.test(text[right])) {
|
|
198
|
+
right += 1;
|
|
199
|
+
}
|
|
200
|
+
return text.slice(left, right).trim().slice(0, 240);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Parse inline suppressions:
|
|
205
|
+
* <!-- dislop-ignore-next-line rule-id -- reason -->
|
|
206
|
+
* /* dislop-ignore-next-line rule-id -- reason *\/
|
|
207
|
+
*/
|
|
208
|
+
export function parseSuppressions(text) {
|
|
209
|
+
const lines = text.split(/\r?\n/);
|
|
210
|
+
const byTargetLine = new Map();
|
|
211
|
+
const directives = [];
|
|
212
|
+
const patterns = [
|
|
213
|
+
/<!--\s*dislop-(?:ignore|disable)-next-line\s+([a-z0-9_*, -]+?)\s*--\s*(.+?)\s*-->/i,
|
|
214
|
+
/\/\*\s*dislop-(?:ignore|disable)-next-line\s+([a-z0-9_*, -]+?)\s*--\s*(.+?)\s*\*\//i,
|
|
215
|
+
];
|
|
216
|
+
|
|
217
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
218
|
+
const line = lines[i];
|
|
219
|
+
for (const pat of patterns) {
|
|
220
|
+
const m = line.match(pat);
|
|
221
|
+
if (m) {
|
|
222
|
+
const ruleIds = m[1]
|
|
223
|
+
.split(/[,\s]+/)
|
|
224
|
+
.map((s) => s.trim())
|
|
225
|
+
.filter(Boolean);
|
|
226
|
+
const reason = m[2].trim();
|
|
227
|
+
let targetLine = i + 2;
|
|
228
|
+
while (targetLine <= lines.length && lines[targetLine - 1].trim() === "") {
|
|
229
|
+
targetLine += 1;
|
|
230
|
+
}
|
|
231
|
+
const entry = {
|
|
232
|
+
directiveLine: i + 1,
|
|
233
|
+
targetLine,
|
|
234
|
+
ruleIds,
|
|
235
|
+
reason,
|
|
236
|
+
used: false,
|
|
237
|
+
};
|
|
238
|
+
directives.push(entry);
|
|
239
|
+
if (!byTargetLine.has(targetLine)) {
|
|
240
|
+
byTargetLine.set(targetLine, []);
|
|
241
|
+
}
|
|
242
|
+
byTargetLine.get(targetLine).push(entry);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { byTargetLine, directives };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Build length-preserving masked views so character offsets match raw text 1:1.
|
|
251
|
+
*/
|
|
252
|
+
export function buildZones(rawText, modality) {
|
|
253
|
+
const normText = String(rawText || "").replace(/\uFEFF/g, " ");
|
|
254
|
+
// Raw zone masks only inline dislop-ignore comment directives themselves
|
|
255
|
+
const raw = normText
|
|
256
|
+
.replace(/<!--\s*dislop-[\s\S]*?-->/gi, preserveLinesBlank)
|
|
257
|
+
.replace(/\/\*\s*dislop-[\s\S]*?\*\//gi, preserveLinesBlank);
|
|
258
|
+
|
|
259
|
+
// Mask quote-specimen blocks BEFORE masking general HTML comments/directives
|
|
260
|
+
let uiText = normText.replace(
|
|
261
|
+
/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi,
|
|
262
|
+
preserveLinesBlank
|
|
263
|
+
);
|
|
264
|
+
// Mask HTML comments (including dislop directives), script, style, code, pre, del, kbd
|
|
265
|
+
uiText = uiText
|
|
266
|
+
.replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
|
|
267
|
+
.replace(/\/\*\s*dislop-[\s\S]*?\*\//gi, preserveLinesBlank)
|
|
268
|
+
.replace(/<(script|style|code|pre|del|kbd)\b[^>]*>[\s\S]*?<\/\1>/gi, preserveLinesBlank);
|
|
269
|
+
|
|
270
|
+
let prose = uiText;
|
|
271
|
+
if (modality === "markdown" || modality === "text") {
|
|
272
|
+
// YAML frontmatter
|
|
273
|
+
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);
|
|
279
|
+
// Inline code spans & strikethrough
|
|
280
|
+
prose = prose.replace(/`[^`\n]+`/g, preserveLinesBlank);
|
|
281
|
+
prose = prose.replace(/~~[^~\n]+~~/g, preserveLinesBlank);
|
|
282
|
+
// 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);
|
|
289
|
+
}
|
|
290
|
+
// Mask bare URLs in prose
|
|
291
|
+
prose = prose.replace(/https?:\/\/[^\s)>"'`]+/g, preserveLinesBlank);
|
|
292
|
+
|
|
293
|
+
if (modality === "html" || modality === "jsx" || modality === "svg") {
|
|
294
|
+
uiText = uiText.replace(/<[^>]+>/g, (tag) => {
|
|
295
|
+
return preserveLinesBlank(tag);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return { raw, prose, "ui-text": uiText };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function isAllowedMatch(matchText, allowList = []) {
|
|
303
|
+
if (!allowList || allowList.length === 0) return false;
|
|
304
|
+
const lower = matchText.toLowerCase();
|
|
305
|
+
return allowList.some((item) => lower.includes(String(item).toLowerCase()));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---------- Structural Prose Probes ----------
|
|
309
|
+
|
|
310
|
+
function probeNegationPivot(proseText, rawText) {
|
|
311
|
+
const hits = [];
|
|
312
|
+
// Chinese: 这不是/这绝非/并非只是/不仅仅是 A,而是/更是 B / 与其说 A,不如说 B
|
|
313
|
+
const zhRegex = /(?:(?:这|那|它)?(?:(?:并)?不(?:是|只是|仅仅?是)|绝非|并非(?:只是)?)|与其说是?)([^,。!?;\n]{1,22})[,,;—]+\s*(?:而是|更是|不如说是?)([^。!?;\n]{1,28})/gu;
|
|
314
|
+
const zhRhetoricalHead = /^(?:(?:这|那|它)|绝非|并非|与其|并?不(?:只是|仅仅?是))/;
|
|
315
|
+
const zhFactualRootCause = /(?:报错|故障|原因|超时|磁盘|内存|耗尽|端口|进程|导致|因为|[A-Za-z_][A-Za-z0-9_-]{2,})/;
|
|
316
|
+
let m;
|
|
317
|
+
while ((m = zhRegex.exec(proseText)) !== null) {
|
|
318
|
+
const clauseA = (m[1] || "").trim();
|
|
319
|
+
const clauseB = (m[2] || "").trim();
|
|
320
|
+
const rawSlice = rawText.slice(m.index, m.index + m[0].length);
|
|
321
|
+
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) {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (!zhRhetoricalHead.test(m[0]) && zhFactualRootCause.test(contextBefore + rawSlice)) {
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// English: (It/This/That/subject) isn't/wasn't (just) X — it's Y / This isn't a X (. / —) it's Y
|
|
337
|
+
const enRegex = /\b(?:(?:(?:it|this|that)(?:'s| is| was)|they(?:'re| are))\s+not|(?:(?:it|this|that|they)\s+)?(?:isn't|wasn't|aren't|is not|was not|are not))\s+(?:just|merely|simply|only)\s+([^.;!?\n—–]{2,50}?)(?:[,;—–-]\s*(?:but|it(?:'s| is| was)|that(?:'s| is| was)|they(?:'re| are))\s+)([^.!?\n]{2,70})|\b(?:It|This|That)\s+(?:isn't|wasn't|is not|was not)\s+(?:a\s+|an\s+|just\s+)?([A-Za-z][A-Za-z0-9 -]{1,32}?)\s*(?:[.!]\s+|[—–-]\s*)(?:it's|it is|it was|that's)\s+([^.!?\n]{2,70})/giu;
|
|
338
|
+
while ((m = enRegex.exec(proseText)) !== null) {
|
|
339
|
+
const clauseA = m[1] || m[3] || "";
|
|
340
|
+
const clauseB = m[2] || m[4] || "";
|
|
341
|
+
const rawSlice = rawText.slice(m.index, m.index + m[0].length);
|
|
342
|
+
if ((/\d/.test(clauseA) && /\d/.test(clauseB)) || /`/.test(rawSlice) || /\.[a-z]{2,4}\b/i.test(rawSlice)) {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
346
|
+
}
|
|
347
|
+
return hits;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function probeStaccatoRun(proseText) {
|
|
351
|
+
const hits = [];
|
|
352
|
+
// Inspect paragraph by paragraph
|
|
353
|
+
const paraRegex = /[^\n]+(?:\n(?!\s*\n)[^\n]+)*/g;
|
|
354
|
+
let pm;
|
|
355
|
+
while ((pm = paraRegex.exec(proseText)) !== null) {
|
|
356
|
+
const para = pm[0];
|
|
357
|
+
const trimmed = para.trim();
|
|
358
|
+
if (!trimmed) continue;
|
|
359
|
+
// Skip headings, lists, tables
|
|
360
|
+
if (/^(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\|)/.test(trimmed)) continue;
|
|
361
|
+
|
|
362
|
+
// Collect sentences with offsets inside paragraph
|
|
363
|
+
const sentRegex = /[^.!?。!?\n]+[.!?。!?]/gu;
|
|
364
|
+
const sentences = [];
|
|
365
|
+
let sm;
|
|
366
|
+
while ((sm = sentRegex.exec(para)) !== null) {
|
|
367
|
+
const s = sm[0].trim();
|
|
368
|
+
if (!s) continue;
|
|
369
|
+
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
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
let runStart = -1;
|
|
384
|
+
let runCount = 0;
|
|
385
|
+
for (let i = 0; i <= sentences.length; i += 1) {
|
|
386
|
+
const cur = sentences[i];
|
|
387
|
+
if (cur && cur.isShort) {
|
|
388
|
+
if (runCount === 0) runStart = i;
|
|
389
|
+
runCount += 1;
|
|
390
|
+
} else {
|
|
391
|
+
if (runCount >= 3) {
|
|
392
|
+
const first = sentences[runStart];
|
|
393
|
+
const last = sentences[i - 1];
|
|
394
|
+
hits.push({ index: first.start, length: last.end - first.start });
|
|
395
|
+
}
|
|
396
|
+
runCount = 0;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return hits;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function probeZhFourCharTriad(proseText) {
|
|
404
|
+
const hits = [];
|
|
405
|
+
const triadRegex = /(?:^|[,。!?;:、“‘(\s]|(?:实现|具备|坚持|保持|做到|形成|打造|追求|提供|确保|了|是|的|以|向|为))([\u4e00-\u9fff]{4})[、,,]\s*([\u4e00-\u9fff]{4})[、,,]\s*([\u4e00-\u9fff]{4})(?=$|[,。!?;:、”’)\s]|[的地等])/gu;
|
|
406
|
+
const entitySuffix = /(?:大学|学院|学校|公司|集团|银行|医院|中心|委员|政府|部门|机场|车站|高速|铁路|[省市区县镇乡])$/u;
|
|
407
|
+
const brokenSlice = /[的了在或与及把被]/u;
|
|
408
|
+
let m;
|
|
409
|
+
while ((m = triadRegex.exec(proseText)) !== null) {
|
|
410
|
+
const items = [m[1], m[2], m[3]];
|
|
411
|
+
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
|
+
const startOffset = m.index + m[0].indexOf(m[1]);
|
|
414
|
+
const prevChar = startOffset > 0 ? proseText[startOffset - 1] : "";
|
|
415
|
+
if (prevChar === "《") continue;
|
|
416
|
+
void triadStr;
|
|
417
|
+
hits.push({ index: startOffset, length: m.index + m[0].length - startOffset });
|
|
418
|
+
}
|
|
419
|
+
return hits;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function probeUnsourcedAttribution(proseText, rawText) {
|
|
423
|
+
const hits = [];
|
|
424
|
+
const attrRegex = /\b(?:[Ss]tudies|[Rr]esearch|[Ii]ndustry\s+research|[Ee]xperts|[Dd]ata)\s+(?:shows?|suggests?|indicates?|proves?)\b|(?:研究|数据|专家|业内人士|行业报告)(?:表明|显示|指出|认为)[,,]?/gu;
|
|
425
|
+
let m;
|
|
426
|
+
while ((m = attrRegex.exec(proseText)) !== null) {
|
|
427
|
+
// Inspect enclosing + lookahead window in rawText for citation markers, links, years, or《report》
|
|
428
|
+
const winStart = Math.max(0, m.index - 30);
|
|
429
|
+
const winEnd = Math.min(rawText.length, m.index + 180);
|
|
430
|
+
const windowRaw = rawText.slice(winStart, winEnd);
|
|
431
|
+
const hasSource =
|
|
432
|
+
/\[\^?\d+\]/.test(windowRaw) ||
|
|
433
|
+
/\]\([^)]+\)/.test(windowRaw) ||
|
|
434
|
+
/https?:\/\//.test(windowRaw) ||
|
|
435
|
+
/\([^()\n]{2,40},\s*(?:19|20)\d{2}[a-z]?\)/.test(windowRaw) ||
|
|
436
|
+
/《[^》\n]{2,30}》/.test(windowRaw) ||
|
|
437
|
+
/(?:见|参见|详见)\s*\[/.test(windowRaw);
|
|
438
|
+
if (!hasSource) {
|
|
439
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return hits;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function probeBoldLeadListWall(proseText, rawText, minRun = 4) {
|
|
446
|
+
const hits = [];
|
|
447
|
+
const lines = rawText.split(/\r?\n/);
|
|
448
|
+
let offset = 0;
|
|
449
|
+
let runStartOffset = 0;
|
|
450
|
+
let runEndOffset = 0;
|
|
451
|
+
let runCount = 0;
|
|
452
|
+
|
|
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) : "";
|
|
456
|
+
const isBullet =
|
|
457
|
+
proseLine.trim().length > 0 &&
|
|
458
|
+
/^\s*(?:[-*+]|\d+[.)])\s+\*\*([^*\n`]{2,36})\*\*\s*[::—-]/.test(line);
|
|
459
|
+
if (isBullet) {
|
|
460
|
+
if (runCount === 0) runStartOffset = offset + line.search(/\S/);
|
|
461
|
+
runCount += 1;
|
|
462
|
+
runEndOffset = offset + line.length;
|
|
463
|
+
} else if (i === lines.length || line.trim() !== "") {
|
|
464
|
+
if (runCount >= minRun) {
|
|
465
|
+
hits.push({ index: runStartOffset, length: runEndOffset - runStartOffset });
|
|
466
|
+
}
|
|
467
|
+
runCount = 0;
|
|
468
|
+
}
|
|
469
|
+
offset += line.length + 1;
|
|
470
|
+
}
|
|
471
|
+
return hits;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function probeEmDashDensity(proseText, maxPer300 = 4) {
|
|
475
|
+
const hits = [];
|
|
476
|
+
const paraRegex = /[^\n]+(?:\n(?!\s*\n)[^\n]+)*/g;
|
|
477
|
+
let pm;
|
|
478
|
+
while ((pm = paraRegex.exec(proseText)) !== null) {
|
|
479
|
+
const para = pm[0];
|
|
480
|
+
if (/^\s*\|/.test(para)) continue;
|
|
481
|
+
// Normalize Chinese `——` as ONE logical dash
|
|
482
|
+
const normalized = para.replace(/——/g, "—");
|
|
483
|
+
const dashes = (normalized.match(/—/g) || []).length;
|
|
484
|
+
if (dashes < 5) continue;
|
|
485
|
+
const cjk = (normalized.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
486
|
+
const enWords = normalized.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
|
|
487
|
+
const units = Math.max(1, enWords + cjk * 0.6);
|
|
488
|
+
const density = (dashes / units) * 300;
|
|
489
|
+
if (density > maxPer300) {
|
|
490
|
+
const firstDash = para.indexOf("—");
|
|
491
|
+
hits.push({ index: pm.index + Math.max(0, firstDash), length: Math.min(para.length, 48) });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return hits;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function probeZhHalfwidthPunctuation(proseText) {
|
|
498
|
+
const hits = [];
|
|
499
|
+
const re = /[\u4e00-\u9fff][,;:!?][\u4e00-\u9fff]/gu;
|
|
500
|
+
let m;
|
|
501
|
+
while ((m = re.exec(proseText)) !== null) {
|
|
502
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
503
|
+
}
|
|
504
|
+
return hits;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ---------- Multi-Angle Text Anti-Slop Probes & Stylometric Profile ----------
|
|
508
|
+
|
|
509
|
+
const ZH_SUBTLE_MARKERS = [
|
|
510
|
+
"有效推动", "持续优化", "显著提升", "进一步助力", "助力", "精细化运营",
|
|
511
|
+
"深度融合", "充分释放", "创新潜能", "高度敏捷", "决策支撑体系", "复杂多变",
|
|
512
|
+
"整体服务质量", "品牌竞争力", "协同效率", "交互体验", "核心竞争力",
|
|
513
|
+
"新篇章", "新台阶", "新阶段", "充分保障", "轻量化交互", "一线响应速度",
|
|
514
|
+
"不可逆转", "集体记忆", "呼吸感", "宏大叙事", "触手可及",
|
|
515
|
+
];
|
|
516
|
+
|
|
517
|
+
const EN_SUBTLE_MARKERS = [
|
|
518
|
+
"leverages", "leverage", "leveraging", "seamlessly", "streamline", "streamlines",
|
|
519
|
+
"foster", "fostering", "robust", "empowers", "empower", "stakeholders",
|
|
520
|
+
"navigate", "comprehensive", "harnesses", "harness", "elevate", "pivotal",
|
|
521
|
+
"transformative", "transformative outcomes", "pivotal alignment", "transparent alignment",
|
|
522
|
+
"resilience", "synergy", "holistic", "ecosystem", "actionable", "unparalleled",
|
|
523
|
+
];
|
|
524
|
+
|
|
525
|
+
const ZH_DISCOURSE_MARKERS = [
|
|
526
|
+
"此外", "与此同时", "不仅如此", "总而言之", "综上所述", "换言之",
|
|
527
|
+
"进一步来看", "诚然", "综合来看", "归根结底",
|
|
528
|
+
];
|
|
529
|
+
|
|
530
|
+
const EN_DISCOURSE_MARKERS = [
|
|
531
|
+
"furthermore", "moreover", "additionally", "consequently",
|
|
532
|
+
"in conclusion", "notably", "at the same time",
|
|
533
|
+
];
|
|
534
|
+
|
|
535
|
+
function escapeRegexLiteral(s) {
|
|
536
|
+
return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function buildAsciiPhraseRegex(phrase, flags = "i") {
|
|
540
|
+
const body = String(phrase)
|
|
541
|
+
.trim()
|
|
542
|
+
.split(/\s+/)
|
|
543
|
+
.map(escapeRegexLiteral)
|
|
544
|
+
.join("\\s+");
|
|
545
|
+
return new RegExp(`(?<![A-Za-z0-9_])${body}(?![A-Za-z0-9_])`, flags);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function clipCodepoints(str, maxLen = 140) {
|
|
549
|
+
const cps = Array.from(String(str || ""));
|
|
550
|
+
return cps.length <= maxLen ? cps.join("") : cps.slice(0, maxLen).join("");
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function roundNonNeg(val, digits = 2) {
|
|
554
|
+
const factor = 10 ** digits;
|
|
555
|
+
return Math.floor(Math.max(0, val) * factor + 0.5) / factor;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// Integer tenths (CJK=6 tenths, EN word=10 tenths) so JS & Python never drift on 0.6 float sums
|
|
559
|
+
function countTextUnitsTenths(s) {
|
|
560
|
+
const cjk = (s.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
561
|
+
const en = (s.match(/[A-Za-z0-9]+/g) || []).length;
|
|
562
|
+
return cjk * 6 + en * 10;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function countTextUnits(s) {
|
|
566
|
+
return countTextUnitsTenths(s) / 10;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function countConcretenessAnchors(rawSlice) {
|
|
570
|
+
// Strip HTML comments before counting concrete anchors
|
|
571
|
+
const s = String(rawSlice || "").replace(/<!--[\s\S]*?-->/g, " ");
|
|
572
|
+
let count = 0;
|
|
573
|
+
count += (s.match(/(?<![A-Za-z0-9_])\d+(?:[.,:]\d+)?%?(?![A-Za-z0-9_])/g) || []).length;
|
|
574
|
+
count += (s.match(/`[^`\n]+`/g) || []).length;
|
|
575
|
+
count += (s.match(/[/\\][A-Za-z0-9._-]+\.[a-z]{1,5}(?![A-Za-z0-9_])/gi) || []).length;
|
|
576
|
+
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
|
+
count += (
|
|
578
|
+
s.match(
|
|
579
|
+
/(?:[一二三四五六七八九十两百千万]+[天月年次个张条座块斤米秒分时]|周[一二三四五六日天]|昨天|昨晚|今早|上周|下周|去年|前年|清晨|傍晚|凌晨|午后|十月|十一月|十二月)/gu
|
|
580
|
+
) || []
|
|
581
|
+
).length;
|
|
582
|
+
return count;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function isStructuredLine(trimmedLine) {
|
|
586
|
+
return /^(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\||>)/.test(trimmedLine);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Linear O(n) prose paragraph extractor that cleanly separates Markdown headings/lists/tables
|
|
591
|
+
* from immediately-following prose lines while preserving exact offsets in `rawText`.
|
|
592
|
+
*/
|
|
593
|
+
function extractProseParagraphs(proseText, rawText) {
|
|
594
|
+
const paras = [];
|
|
595
|
+
const n = proseText.length;
|
|
596
|
+
let pos = 0;
|
|
597
|
+
let curStart = -1;
|
|
598
|
+
let curEnd = -1;
|
|
599
|
+
|
|
600
|
+
function flush() {
|
|
601
|
+
if (curStart === -1 || curEnd <= curStart) {
|
|
602
|
+
curStart = -1;
|
|
603
|
+
curEnd = -1;
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
const text = proseText.slice(curStart, curEnd);
|
|
607
|
+
const trimmed = text.trim();
|
|
608
|
+
if (trimmed) {
|
|
609
|
+
const lead = text.indexOf(trimmed);
|
|
610
|
+
const start = curStart + Math.max(0, lead);
|
|
611
|
+
const rawSlice = rawText.slice(curStart, curEnd);
|
|
612
|
+
paras.push({ start, end: curEnd, base: curStart, text, trimmed, rawSlice });
|
|
613
|
+
}
|
|
614
|
+
curStart = -1;
|
|
615
|
+
curEnd = -1;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
while (pos <= n) {
|
|
619
|
+
let nl = proseText.indexOf("\n", pos);
|
|
620
|
+
const lineEnd = nl === -1 ? n : nl;
|
|
621
|
+
const lineProse = proseText.slice(pos, lineEnd);
|
|
622
|
+
const lineRaw = rawText.slice(pos, lineEnd);
|
|
623
|
+
const trimProse = lineProse.trim();
|
|
624
|
+
const trimRaw = lineRaw.trim();
|
|
625
|
+
|
|
626
|
+
if (!trimProse || isStructuredLine(trimProse) || isStructuredLine(trimRaw)) {
|
|
627
|
+
flush();
|
|
628
|
+
} else {
|
|
629
|
+
if (curStart === -1) curStart = pos;
|
|
630
|
+
curEnd = lineEnd;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (nl === -1) break;
|
|
634
|
+
pos = nl + 1;
|
|
635
|
+
}
|
|
636
|
+
flush();
|
|
637
|
+
return paras;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Linear O(n) sentence splitter with exact source offsets — zero regex backtracking.
|
|
642
|
+
*/
|
|
643
|
+
function splitProseSentencesWithOffsets(para) {
|
|
644
|
+
const out = [];
|
|
645
|
+
const text = para.text;
|
|
646
|
+
const base = para.base ?? (para.end - text.length);
|
|
647
|
+
const n = text.length;
|
|
648
|
+
let i = 0;
|
|
649
|
+
const isEndPunct = (ch) => ch === "。" || ch === "!" || ch === "?" || ch === "." || ch === "!" || ch === "?";
|
|
650
|
+
|
|
651
|
+
while (i < n) {
|
|
652
|
+
while (i < n && (text[i] === "\n" || text[i] === "\r" || text[i] === " " || text[i] === "\t")) {
|
|
653
|
+
i += 1;
|
|
654
|
+
}
|
|
655
|
+
if (i >= n) break;
|
|
656
|
+
const segStart = i;
|
|
657
|
+
while (i < n && text[i] !== "\n" && !isEndPunct(text[i])) {
|
|
658
|
+
i += 1;
|
|
659
|
+
}
|
|
660
|
+
while (i < n && isEndPunct(text[i])) {
|
|
661
|
+
i += 1;
|
|
662
|
+
}
|
|
663
|
+
let segEnd = i;
|
|
664
|
+
while (segEnd > segStart && (text[segEnd - 1] === " " || text[segEnd - 1] === "\t" || text[segEnd - 1] === "\r")) {
|
|
665
|
+
segEnd -= 1;
|
|
666
|
+
}
|
|
667
|
+
if (segEnd - segStart >= 3) {
|
|
668
|
+
out.push({ start: base + segStart, end: base + segEnd, text: text.slice(segStart, segEnd) });
|
|
669
|
+
}
|
|
670
|
+
if (i < n && text[i] === "\n") i += 1;
|
|
671
|
+
}
|
|
672
|
+
return out;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function probeCooccurrenceSlopCluster(proseText, rawText) {
|
|
676
|
+
const hits = [];
|
|
677
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
678
|
+
const enSciRobustRe =
|
|
679
|
+
/(?<![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) {
|
|
681
|
+
const found = new Map();
|
|
682
|
+
const paraBase = para.base;
|
|
683
|
+
for (const term of ZH_SUBTLE_MARKERS) {
|
|
684
|
+
const idx = para.text.indexOf(term);
|
|
685
|
+
if (idx !== -1) {
|
|
686
|
+
if (term === "助力" && found.has("进一步助力")) continue;
|
|
687
|
+
found.set(term, { start: paraBase + idx, end: paraBase + idx + term.length });
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
const lowPara = para.text.toLowerCase().replace(enSciRobustRe, (m) => " ".repeat(m.length));
|
|
691
|
+
for (const term of EN_SUBTLE_MARKERS) {
|
|
692
|
+
const re = buildAsciiPhraseRegex(term, "i");
|
|
693
|
+
const m = re.exec(lowPara);
|
|
694
|
+
if (m) {
|
|
695
|
+
const stem = term.replace(/(?:ing|es|s)$/, "");
|
|
696
|
+
if (!found.has(`en:${stem}`)) {
|
|
697
|
+
found.set(`en:${stem}`, { start: paraBase + m.index, end: paraBase + m.index + m[0].length });
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const distinct = found.size;
|
|
702
|
+
if (distinct < 2) continue;
|
|
703
|
+
const unitsTenths = Math.max(10, countTextUnitsTenths(para.text));
|
|
704
|
+
const concreteness = (countConcretenessAnchors(para.rawSlice) * 1000) / unitsTenths;
|
|
705
|
+
if (distinct >= 3 || (distinct >= 2 && concreteness < 6.0)) {
|
|
706
|
+
const spans = Array.from(found.values()).sort((a, b) => a.start - b.start);
|
|
707
|
+
const first = spans[0].start;
|
|
708
|
+
const last = spans[spans.length - 1].end;
|
|
709
|
+
hits.push({ index: first, length: Math.min(140, Math.max(1, last - first)) });
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return hits;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function probeSemicolonTricolon(proseText, rawText) {
|
|
716
|
+
const hits = [];
|
|
717
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
718
|
+
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
|
|
721
|
+
const maskedPara = para.text
|
|
722
|
+
.replace(/\([^)\n]*[;;][^)\n]*\)/g, (m) => " ".repeat(m.length))
|
|
723
|
+
.replace(/([^)\n]*[;;][^)\n]*)/g, (m) => " ".repeat(m.length))
|
|
724
|
+
.replace(/“[^”\n]*[;;][^”\n]*”/g, (m) => " ".repeat(m.length))
|
|
725
|
+
.replace(/"[^"\n]*[;;][^"\n]*"/g, (m) => " ".repeat(m.length));
|
|
726
|
+
const maskedObj = { ...para, text: maskedPara };
|
|
727
|
+
const sents = splitProseSentencesWithOffsets(maskedObj);
|
|
728
|
+
for (const s of sents) {
|
|
729
|
+
if (/[A-Za-z0-9_-]+\s*[:=]\s*[^;;\n]+[;;]/.test(s.text)) continue;
|
|
730
|
+
if (/^[^;;。!?.!?\n]{2,32}[::]/.test(s.text)) continue;
|
|
731
|
+
if (legalGuard.test(s.text)) continue;
|
|
732
|
+
const rawSent = rawText.slice(s.start, s.end);
|
|
733
|
+
const techRefs = (rawSent.match(/`[^`\n]+`|\]\([^)\n]+\)/g) || []).length;
|
|
734
|
+
if (techRefs >= 2) continue;
|
|
735
|
+
const semis = (s.text.match(/[;;]/g) || []).length;
|
|
736
|
+
if (semis >= 2) {
|
|
737
|
+
hits.push({ index: s.start, length: Math.min(140, s.text.length) });
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return hits;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function probeRhetoricalQaCadence(proseText, rawText) {
|
|
745
|
+
const hits = [];
|
|
746
|
+
// Run per prose paragraph so FAQ headings (`# Why...?`) followed by answers never false-trigger
|
|
747
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
748
|
+
for (const para of paras) {
|
|
749
|
+
const base = para.base;
|
|
750
|
+
const text = para.text;
|
|
751
|
+
const zhQa = /(?:为什么|为何)[^??\n]{3,35}[??]\s*(?:因为|原因(?:很|其实)?(?:简单|在于))/gu;
|
|
752
|
+
let m;
|
|
753
|
+
while ((m = zhQa.exec(text)) !== null) {
|
|
754
|
+
const absIdx = base + m.index;
|
|
755
|
+
const prev = absIdx > 0 ? rawText[absIdx - 1] : "";
|
|
756
|
+
if (/[::“"「『]/.test(prev)) continue;
|
|
757
|
+
hits.push({ index: absIdx, length: m[0].length });
|
|
758
|
+
}
|
|
759
|
+
const zhPunch = /(?:^|[。!?\n]\s*)(?:结果呢|原因呢|真相呢|代价呢)[??]/gu;
|
|
760
|
+
while ((m = zhPunch.exec(text)) !== null) {
|
|
761
|
+
const lead = m[0].match(/^[。!?\s]+/);
|
|
762
|
+
const offset = lead ? lead[0].length : 0;
|
|
763
|
+
hits.push({ index: base + m.index + offset, length: m[0].length - offset });
|
|
764
|
+
}
|
|
765
|
+
const enQa = /(?<![A-Za-z0-9_])Why\s+(?:do|does|did|is|are)\s+[^?\n]{6,80}\?\s*Because(?![A-Za-z0-9_])/giu;
|
|
766
|
+
while ((m = enQa.exec(text)) !== null) {
|
|
767
|
+
hits.push({ index: base + m.index, length: m[0].length });
|
|
768
|
+
}
|
|
769
|
+
const enPunch = /(?:^|[.!?]\s+)(?:The\s+(?:result|reason|catch|truth|reality|secret))\?\s+[A-Z]/gu;
|
|
770
|
+
while ((m = enPunch.exec(text)) !== null) {
|
|
771
|
+
const lead = m[0].match(/^[.!?\s]+/);
|
|
772
|
+
const offset = lead ? lead[0].length : 0;
|
|
773
|
+
hits.push({ index: base + m.index + offset, length: m[0].length - offset });
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
return hits;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function probeCommaChainRunon(proseText, rawText) {
|
|
780
|
+
const hits = [];
|
|
781
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
782
|
+
for (const para of paras) {
|
|
783
|
+
const sents = splitProseSentencesWithOffsets(para);
|
|
784
|
+
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, " ");
|
|
790
|
+
const commas = (cleaned.match(/[,,]/g) || []).length;
|
|
791
|
+
if (commas < 5) continue;
|
|
792
|
+
const parts = cleaned.split(/[,,]/).map((p) => p.trim()).filter(Boolean);
|
|
793
|
+
if (parts.length < 6) continue;
|
|
794
|
+
// Distinguish genuine multi-clause run-ons from short noun-phrase enumerations ("a, b, c, d, e, and f")
|
|
795
|
+
let clauseParts = 0;
|
|
796
|
+
for (const p of parts) {
|
|
797
|
+
const cjk = (p.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
798
|
+
const enWords = (p.match(/[A-Za-z]+/g) || []).length;
|
|
799
|
+
const hasGerundOrVerb = /\b[a-z]{3,}ing\b/i.test(p);
|
|
800
|
+
if (cjk >= 6 || enWords >= 4 || (enWords >= 3 && hasGerundOrVerb)) clauseParts += 1;
|
|
801
|
+
}
|
|
802
|
+
if (clauseParts < 5) continue;
|
|
803
|
+
hits.push({ index: s.start, length: Math.min(140, s.text.length) });
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return hits;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function probeNarrativeSandwichFrame(proseText, rawText) {
|
|
810
|
+
const hits = [];
|
|
811
|
+
const patterns = [
|
|
812
|
+
/(?:^|\n\s*)(?:随着[^,。\n]{2,18}(?:飞速|快速|不断|持续)(?:发展|深入|演进|推进)|在(?:当今|快节奏的)[^,。\n]{2,16}(?:时代|生活|社会)中?)/gu,
|
|
813
|
+
/(?:^|\n\s*)(?:As\s+(?:organizations|teams|companies|distributed\s+teams)\s+(?:navigate|scale|adapt)[^,.\n]{2,60}|In\s+an\s+era\s+(?:defined\s+by|of|where)[^,.\n]{2,60})/giu,
|
|
814
|
+
/(?:展望未来[,,]|携手[^,。!?\n]{1,16}(?:开启|迈向)[^。!?\n]{2,20}|必将迎来[^。!?\n]{2,16}|值得每一个[^。!?\n]{2,16}深思)/gu,
|
|
815
|
+
/\b(?:Looking\s+ahead,|Moving\s+forward,)[^.!?\n]{5,120}(?:well-positioned\s+to\s+thrive|vital\s+role|essential\s+for|year\s+ahead|remind\s+us)\b/giu,
|
|
816
|
+
];
|
|
817
|
+
for (const re of patterns) {
|
|
818
|
+
let m;
|
|
819
|
+
while ((m = re.exec(proseText)) !== null) {
|
|
820
|
+
const lead = m[0].match(/^\s+/);
|
|
821
|
+
const off = lead ? lead[0].length : 0;
|
|
822
|
+
hits.push({ index: m.index + off, length: m[0].length - off });
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// Discourse-marker cluster: >= 3 distinct/repeated stock transitions in prose
|
|
827
|
+
const discHits = [];
|
|
828
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
829
|
+
for (const para of paras) {
|
|
830
|
+
const paraBase = para.base;
|
|
831
|
+
for (const marker of ZH_DISCOURSE_MARKERS) {
|
|
832
|
+
let pos = 0;
|
|
833
|
+
while ((pos = para.text.indexOf(marker, pos)) !== -1) {
|
|
834
|
+
discHits.push({ index: paraBase + pos, length: marker.length });
|
|
835
|
+
pos += marker.length;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const low = para.text.toLowerCase();
|
|
839
|
+
for (const marker of EN_DISCOURSE_MARKERS) {
|
|
840
|
+
const re = buildAsciiPhraseRegex(marker, "gi");
|
|
841
|
+
let m;
|
|
842
|
+
while ((m = re.exec(low)) !== null) {
|
|
843
|
+
discHits.push({ index: paraBase + m.index, length: m[0].length });
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (discHits.length >= 3) {
|
|
848
|
+
discHits.sort((a, b) => a.index - b.index);
|
|
849
|
+
const first = discHits[0];
|
|
850
|
+
const third = discHits[2];
|
|
851
|
+
hits.push({
|
|
852
|
+
index: first.index,
|
|
853
|
+
length: Math.min(140, Math.max(first.length, third.index + third.length - first.index)),
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
return hits;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function classifyOpenerSkeleton(text, explicitOnly = false) {
|
|
860
|
+
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)) {
|
|
863
|
+
return null;
|
|
864
|
+
}
|
|
865
|
+
if (/^在[\u4e00-\u9fff]{2,6}方面[,,]/.test(s)) return "ZH_ZAI_X_FANGMIAN";
|
|
866
|
+
if (/^(?:首先|其次|再次|最后)[,,]/.test(s)) return "ZH_ORDINAL_STEP";
|
|
867
|
+
if (/^By\s+[a-z]+ing\b/i.test(s)) return "EN_BY_GERUND";
|
|
868
|
+
if (/^(?:First|Second|Third|Fourth|Finally|Lastly),\s+/i.test(s)) return "EN_ORDINAL_STEP";
|
|
869
|
+
if (explicitOnly) return null;
|
|
870
|
+
if (s.length < 24) return null;
|
|
871
|
+
const enPre = s.match(/^([A-Za-z]+\s+[A-Za-z]+)\b/);
|
|
872
|
+
if (enPre) {
|
|
873
|
+
const low = enPre[1].toLowerCase();
|
|
874
|
+
// Skip very generic determiner pairs like "in the", "of the", "it is"
|
|
875
|
+
if (!/^(?:in the|on the|at the|of the|to the|it is|this is|there is|we have|we are|the [a-z]+)$/.test(low)) {
|
|
876
|
+
return `EN_PRE:${low}`;
|
|
877
|
+
}
|
|
878
|
+
return null;
|
|
879
|
+
}
|
|
880
|
+
const zhPre = s.match(/^([\u4e00-\u9fff]{3})/);
|
|
881
|
+
if (zhPre) return `ZH_PRE:${zhPre[1]}`;
|
|
882
|
+
return null;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function hasRepeatedPostOrdinalStem(items) {
|
|
886
|
+
const stems = new Map();
|
|
887
|
+
for (const it of items) {
|
|
888
|
+
const rest = it.text
|
|
889
|
+
.replace(/^(?:首先|其次|再次|最后|First|Second|Third|Fourth|Finally|Lastly)[,,]\s*/i, "")
|
|
890
|
+
.trim();
|
|
891
|
+
const mEn = rest.match(/^([A-Za-z]+(?:\s+[A-Za-z-]+){0,2})/);
|
|
892
|
+
const mZh = rest.match(/^([\u4e00-\u9fff]{2,4})/);
|
|
893
|
+
const key = mEn ? `en:${mEn[1].toLowerCase()}` : mZh ? `zh:${mZh[1]}` : null;
|
|
894
|
+
if (!key) continue;
|
|
895
|
+
stems.set(key, (stems.get(key) || 0) + 1);
|
|
896
|
+
if (stems.get(key) >= 2) return true;
|
|
897
|
+
}
|
|
898
|
+
return false;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
function probeTemplateSkeletonEcho(proseText, rawText) {
|
|
902
|
+
const hits = [];
|
|
903
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
904
|
+
|
|
905
|
+
function checkItems(items, explicitOnly, insideSinglePara) {
|
|
906
|
+
const groups = new Map();
|
|
907
|
+
for (const item of items) {
|
|
908
|
+
const skel = classifyOpenerSkeleton(item.text, explicitOnly);
|
|
909
|
+
if (!skel) continue;
|
|
910
|
+
if (!groups.has(skel)) groups.set(skel, []);
|
|
911
|
+
groups.get(skel).push(item);
|
|
912
|
+
}
|
|
913
|
+
for (const [skel, matched] of groups.entries()) {
|
|
914
|
+
if (matched.length >= 3) {
|
|
915
|
+
if (
|
|
916
|
+
insideSinglePara &&
|
|
917
|
+
(skel === "EN_ORDINAL_STEP" || skel === "ZH_ORDINAL_STEP") &&
|
|
918
|
+
!hasRepeatedPostOrdinalStem(matched)
|
|
919
|
+
) {
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
hits.push({ index: matched[0].start, length: Math.min(120, matched[0].text.length) });
|
|
923
|
+
return true;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
return false;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
if (paras.length >= 3) {
|
|
930
|
+
if (checkItems(paras.map((p) => ({ start: p.start, text: p.trimmed })), false, false)) {
|
|
931
|
+
return hits;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const allSents = [];
|
|
935
|
+
for (const para of paras) {
|
|
936
|
+
for (const s of splitProseSentencesWithOffsets(para)) {
|
|
937
|
+
allSents.push(s);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
if (allSents.length >= 3) {
|
|
941
|
+
checkItems(allSents, true, true);
|
|
942
|
+
}
|
|
943
|
+
return hits;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
function probeLowBurstinessVapor(proseText, rawText) {
|
|
947
|
+
const paras = extractProseParagraphs(proseText, rawText);
|
|
948
|
+
if (paras.length === 0) return [];
|
|
949
|
+
const sents = [];
|
|
950
|
+
for (const para of paras) {
|
|
951
|
+
for (const s of splitProseSentencesWithOffsets(para)) {
|
|
952
|
+
const u = countTextUnitsTenths(s.text);
|
|
953
|
+
if (u > 0) sents.push({ ...s, tenths: u });
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
if (sents.length < 5) return [];
|
|
957
|
+
const sumTenths = sents.reduce((a, b) => a + b.tenths, 0);
|
|
958
|
+
const meanTenths = sumTenths / sents.length;
|
|
959
|
+
if (meanTenths <= 0) return [];
|
|
960
|
+
const varianceTenths = sents.reduce((a, b) => a + (b.tenths - meanTenths) ** 2, 0) / sents.length;
|
|
961
|
+
const cv = Math.sqrt(varianceTenths) / meanTenths;
|
|
962
|
+
const totalTenths = Math.max(10, sumTenths);
|
|
963
|
+
const totalAnchors = paras.reduce((acc, p) => acc + countConcretenessAnchors(p.rawSlice), 0);
|
|
964
|
+
const concreteness = (totalAnchors * 1000) / totalTenths;
|
|
965
|
+
if (cv < 0.24 && concreteness < 1.5) {
|
|
966
|
+
return [{ index: paras[0].start, length: Math.min(80, paras[0].trimmed.length) }];
|
|
967
|
+
}
|
|
968
|
+
return [];
|
|
969
|
+
}
|
|
970
|
+
|
|
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);
|
|
985
|
+
if (u > 0) sents.push({ ...s, tenths: u });
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
const nSents = sents.length;
|
|
990
|
+
let meanLen = 0;
|
|
991
|
+
let cv = 0;
|
|
992
|
+
let adjContrast = 0;
|
|
993
|
+
if (nSents >= 2) {
|
|
994
|
+
const sumTenths = sents.reduce((a, b) => a + b.tenths, 0);
|
|
995
|
+
const meanTenths = sumTenths / nSents;
|
|
996
|
+
meanLen = meanTenths / 10;
|
|
997
|
+
const varianceTenths = sents.reduce((a, b) => a + (b.tenths - meanTenths) ** 2, 0) / nSents;
|
|
998
|
+
cv = meanTenths > 0 ? Math.sqrt(varianceTenths) / meanTenths : 0;
|
|
999
|
+
let diffSumTenths = 0;
|
|
1000
|
+
for (let i = 1; i < nSents; i += 1) diffSumTenths += Math.abs(sents[i].tenths - sents[i - 1].tenths);
|
|
1001
|
+
adjContrast = meanTenths > 0 ? (diffSumTenths / (nSents - 1)) / meanTenths : 0;
|
|
1002
|
+
} else if (nSents === 1) {
|
|
1003
|
+
meanLen = sents[0].tenths / 10;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
const joinedProse = paras.map((p) => p.trimmed).join("\n");
|
|
1007
|
+
const totalTenths = Math.max(10, countTextUnitsTenths(joinedProse));
|
|
1008
|
+
const totalUnits = totalTenths / 10;
|
|
1009
|
+
|
|
1010
|
+
// Lexical diversity (TTR + Moving-Average TTR window 25 step 5) + bigram echo + char Shannon entropy
|
|
1011
|
+
const tokens = (joinedProse.toLowerCase().match(/[\u4e00-\u9fff]|[a-z]{2,}/gu) || []);
|
|
1012
|
+
const nTok = tokens.length;
|
|
1013
|
+
const ttr = nTok > 0 ? new Set(tokens).size / nTok : 0;
|
|
1014
|
+
let mattr = ttr;
|
|
1015
|
+
const win = 25;
|
|
1016
|
+
if (nTok > win) {
|
|
1017
|
+
let sum = 0;
|
|
1018
|
+
let steps = 0;
|
|
1019
|
+
for (let i = 0; i <= nTok - win; i += 5) {
|
|
1020
|
+
sum += new Set(tokens.slice(i, i + win)).size / win;
|
|
1021
|
+
steps += 1;
|
|
1022
|
+
}
|
|
1023
|
+
mattr = steps > 0 ? sum / steps : ttr;
|
|
1024
|
+
}
|
|
1025
|
+
let bigramEcho = 0;
|
|
1026
|
+
if (nTok >= 2) {
|
|
1027
|
+
const bSet = new Set();
|
|
1028
|
+
for (let i = 0; i < nTok - 1; i += 1) bSet.add(`${tokens[i]}|${tokens[i + 1]}`);
|
|
1029
|
+
bigramEcho = 1 - bSet.size / (nTok - 1);
|
|
1030
|
+
}
|
|
1031
|
+
let charEntropy = 0;
|
|
1032
|
+
const chars = Array.from(joinedProse);
|
|
1033
|
+
if (chars.length > 0) {
|
|
1034
|
+
const counts = new Map();
|
|
1035
|
+
for (const ch of chars) counts.set(ch, (counts.get(ch) || 0) + 1);
|
|
1036
|
+
for (const c of counts.values()) {
|
|
1037
|
+
const p = c / chars.length;
|
|
1038
|
+
charEntropy -= p * Math.log2(p);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
const anchorCount = paras.reduce((acc, p) => acc + countConcretenessAnchors(p.rawSlice), 0);
|
|
1043
|
+
const concretenessPer100 = (anchorCount / totalUnits) * 100;
|
|
1044
|
+
|
|
1045
|
+
// Punctuation
|
|
1046
|
+
const emDashes = (joinedProse.replace(/——/g, "—").match(/—/g) || []).length;
|
|
1047
|
+
const emDashPer300 = (emDashes / totalUnits) * 300;
|
|
1048
|
+
let maxSemi = 0;
|
|
1049
|
+
let maxComma = 0;
|
|
1050
|
+
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;
|
|
1053
|
+
if (sc > maxSemi) maxSemi = sc;
|
|
1054
|
+
if (cc > maxComma) maxComma = cc;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
const coocHits = probeCooccurrenceSlopCluster(prose, raw).length;
|
|
1058
|
+
const semiHits = probeSemicolonTricolon(prose, raw).length;
|
|
1059
|
+
const rhetQaCount = probeRhetoricalQaCadence(prose, raw).length;
|
|
1060
|
+
const commaHits = probeCommaChainRunon(prose, raw).length;
|
|
1061
|
+
const skelHits = probeTemplateSkeletonEcho(prose, raw).length;
|
|
1062
|
+
const narrativeHits = probeNarrativeSandwichFrame(prose, raw).length;
|
|
1063
|
+
const vaporHits = probeLowBurstinessVapor(prose, raw).length;
|
|
1064
|
+
|
|
1065
|
+
// Transparent, non-black-box telemetry score (0-100)
|
|
1066
|
+
const signals = [];
|
|
1067
|
+
let riskScore = 0;
|
|
1068
|
+
if (coocHits > 0) { riskScore += 28; signals.push("cooccurrence-slop-cluster"); }
|
|
1069
|
+
if (semiHits > 0) { riskScore += 24; signals.push("semicolon-tricolon"); }
|
|
1070
|
+
if (rhetQaCount > 0) { riskScore += 24; signals.push("rhetorical-qa-cadence"); }
|
|
1071
|
+
if (commaHits > 0) { riskScore += 18; signals.push("comma-chain-runon"); }
|
|
1072
|
+
if (narrativeHits > 0) { riskScore += 26; signals.push("narrative-sandwich-frame"); }
|
|
1073
|
+
if (skelHits > 0) { riskScore += 26; signals.push("template-skeleton-echo"); }
|
|
1074
|
+
if (vaporHits > 0) { riskScore += 24; signals.push("low-burstiness-vapor"); }
|
|
1075
|
+
else if (nSents >= 5 && cv < 0.24) { riskScore += 10; signals.push("flat-sentence-rhythm"); }
|
|
1076
|
+
if (nSents >= 3 && anchorCount === 0) { riskScore += 10; signals.push("zero-concrete-anchors"); }
|
|
1077
|
+
if (emDashPer300 > 4 && emDashes >= 5) { riskScore += 12; signals.push("high-em-dash-density"); }
|
|
1078
|
+
riskScore = Math.min(100, riskScore);
|
|
1079
|
+
|
|
1080
|
+
const burstinessStatus = nSents < 3 ? "short" : cv < 0.24 ? "flat" : cv >= 0.35 ? "varied" : "moderate";
|
|
1081
|
+
const concretenessStatus = concretenessPer100 >= 4.0 ? "grounded" : concretenessPer100 >= 1.5 ? "moderate" : "vapor";
|
|
1082
|
+
const riskLevel = riskScore >= 45 ? "high" : riskScore >= 20 ? "medium" : "low";
|
|
1083
|
+
|
|
1084
|
+
return {
|
|
1085
|
+
schema: "dislop.text-profile/1",
|
|
1086
|
+
sentenceCount: nSents,
|
|
1087
|
+
paragraphCount: paras.length,
|
|
1088
|
+
unitCount: roundNonNeg(totalUnits, 1),
|
|
1089
|
+
burstiness: {
|
|
1090
|
+
meanLength: roundNonNeg(meanLen, 1),
|
|
1091
|
+
cv: roundNonNeg(cv, 2),
|
|
1092
|
+
adjacentContrast: roundNonNeg(adjContrast, 2),
|
|
1093
|
+
status: burstinessStatus,
|
|
1094
|
+
},
|
|
1095
|
+
lexical: {
|
|
1096
|
+
ttr: roundNonNeg(ttr, 2),
|
|
1097
|
+
mattr: roundNonNeg(mattr, 2),
|
|
1098
|
+
bigramEcho: roundNonNeg(bigramEcho, 2),
|
|
1099
|
+
charEntropy: roundNonNeg(charEntropy, 2),
|
|
1100
|
+
cooccurrenceClusters: coocHits,
|
|
1101
|
+
},
|
|
1102
|
+
concreteness: {
|
|
1103
|
+
anchorCount,
|
|
1104
|
+
per100Units: roundNonNeg(concretenessPer100, 1),
|
|
1105
|
+
status: concretenessStatus,
|
|
1106
|
+
},
|
|
1107
|
+
punctuation: {
|
|
1108
|
+
emDashPer300: roundNonNeg(emDashPer300, 1),
|
|
1109
|
+
maxSemicolonsInSentence: maxSemi,
|
|
1110
|
+
maxCommasInSentence: maxComma,
|
|
1111
|
+
rhetoricalQaCount: rhetQaCount,
|
|
1112
|
+
},
|
|
1113
|
+
structure: {
|
|
1114
|
+
skeletonEchoHits: skelHits,
|
|
1115
|
+
narrativeFrameHits: narrativeHits,
|
|
1116
|
+
lowBurstinessVapor: vaporHits > 0,
|
|
1117
|
+
},
|
|
1118
|
+
telemetryRisk: {
|
|
1119
|
+
score: riskScore,
|
|
1120
|
+
level: riskLevel,
|
|
1121
|
+
signals,
|
|
1122
|
+
},
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// ---------- UI, CSS, HTML & SVG Probes ----------
|
|
1127
|
+
|
|
1128
|
+
function parseColorRgb(raw) {
|
|
1129
|
+
if (!raw) return null;
|
|
1130
|
+
const val = raw.trim().toLowerCase();
|
|
1131
|
+
const hex6 = val.match(/^#([0-9a-f]{6})$/i);
|
|
1132
|
+
if (hex6) {
|
|
1133
|
+
const n = parseInt(hex6[1], 16);
|
|
1134
|
+
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
1135
|
+
}
|
|
1136
|
+
const hex3 = val.match(/^#([0-9a-f]{3})$/i);
|
|
1137
|
+
if (hex3) {
|
|
1138
|
+
const [r, g, b] = hex3[1].split("").map((c) => parseInt(c + c, 16));
|
|
1139
|
+
return [r, g, b];
|
|
1140
|
+
}
|
|
1141
|
+
const rgb = val.match(/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i);
|
|
1142
|
+
if (rgb) {
|
|
1143
|
+
return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
|
|
1144
|
+
}
|
|
1145
|
+
if (val === "white") return [255, 255, 255];
|
|
1146
|
+
if (val === "black") return [0, 0, 0];
|
|
1147
|
+
return null;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
function rgbToHsl([r, g, b]) {
|
|
1151
|
+
const rn = r / 255;
|
|
1152
|
+
const gn = g / 255;
|
|
1153
|
+
const bn = b / 255;
|
|
1154
|
+
const max = Math.max(rn, gn, bn);
|
|
1155
|
+
const min = Math.min(rn, gn, bn);
|
|
1156
|
+
const l = (max + min) / 2;
|
|
1157
|
+
if (max === min) return [0, 0, l * 100];
|
|
1158
|
+
const d = max - min;
|
|
1159
|
+
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
|
1160
|
+
let h = 0;
|
|
1161
|
+
if (max === rn) h = (gn - bn) / d + (gn < bn ? 6 : 0);
|
|
1162
|
+
else if (max === gn) h = (bn - rn) / d + 2;
|
|
1163
|
+
else h = (rn - gn) / d + 4;
|
|
1164
|
+
return [h * 60, s * 100, l * 100];
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
function probeUiDeadControl(rawText) {
|
|
1168
|
+
const clean = rawText
|
|
1169
|
+
.replace(/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi, preserveLinesBlank)
|
|
1170
|
+
.replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
|
|
1171
|
+
.replace(/<(script|style|code|pre)\b[^>]*>[\s\S]*?<\/\1>/gi, preserveLinesBlank);
|
|
1172
|
+
|
|
1173
|
+
const hits = [];
|
|
1174
|
+
// 1. Dead anchors: <a href="#"> / href="" / href="javascript:..." without click handler
|
|
1175
|
+
const anchorRe = /<a\b([^>]*)>/gi;
|
|
1176
|
+
let m;
|
|
1177
|
+
while ((m = anchorRe.exec(clean)) !== null) {
|
|
1178
|
+
const attrs = m[1] || "";
|
|
1179
|
+
const hrefMatch = attrs.match(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
|
1180
|
+
const href = hrefMatch ? (hrefMatch[1] ?? hrefMatch[2] ?? "").trim() : null;
|
|
1181
|
+
const hasHandler = /\b(?:onClick|onclick|@click|hx-get|hx-post)\b/.test(attrs);
|
|
1182
|
+
if (!hasHandler && (href === "#" || href === "" || (href && /^javascript:/i.test(href)))) {
|
|
1183
|
+
hits.push({ index: m.index, length: m[0].length, severity: "error" });
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// 2. Empty or unexplained static disabled <button>
|
|
1188
|
+
const btnRe = /<button\b([^>]*)>([\s\S]*?)<\/button>/gi;
|
|
1189
|
+
while ((m = btnRe.exec(clean)) !== null) {
|
|
1190
|
+
const attrs = m[1] || "";
|
|
1191
|
+
const inner = (m[2] || "").replace(/<[^>]+>/g, "").trim();
|
|
1192
|
+
const hasLabel = inner.length > 0 || /\b(?:aria-label|aria-labelledby|title)\s*=\s*["'][^"']+["']/i.test(attrs);
|
|
1193
|
+
if (!hasLabel && !/\{\.\.\./.test(attrs)) {
|
|
1194
|
+
hits.push({ index: m.index, length: m[0].length, severity: "error" });
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
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) {
|
|
1200
|
+
hits.push({ index: m.index, length: m[0].length, severity: "warning" });
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
return hits;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
function probeUiAiGradient(rawText) {
|
|
1207
|
+
const clean = rawText
|
|
1208
|
+
.replace(/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi, preserveLinesBlank)
|
|
1209
|
+
.replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
|
|
1210
|
+
.replace(/\/\*[\s\S]*?\*\//g, preserveLinesBlank)
|
|
1211
|
+
.replace(/<(script|code|pre)\b[^>]*>[\s\S]*?<\/\1>/gi, preserveLinesBlank);
|
|
1212
|
+
|
|
1213
|
+
const hits = [];
|
|
1214
|
+
// 1. Tailwind purple/indigo/violet + pink/fuchsia/purple gradient or gradient-clipped text
|
|
1215
|
+
const twRe = /\b(?:from-(?:indigo|purple|violet)-\d{2,3}[^"'\n>]{0,60}(?:to|via)-(?:purple|pink|fuchsia|violet)-\d{2,3}|bg-clip-text\s+text-transparent|text-transparent\s+bg-clip-text)\b/gi;
|
|
1216
|
+
let m;
|
|
1217
|
+
while ((m = twRe.exec(clean)) !== null) {
|
|
1218
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// 2. CSS gradient with purple-pink hex stops or background-clip: text
|
|
1222
|
+
const cssGradRe = /(?:linear|radial)-gradient\(([^)]+)\)/gi;
|
|
1223
|
+
while ((m = cssGradRe.exec(clean)) !== null) {
|
|
1224
|
+
const hexes = m[1].match(/#[0-9a-fA-F]{3,6}\b/g) || [];
|
|
1225
|
+
let purplePinkStops = 0;
|
|
1226
|
+
for (const hx of hexes) {
|
|
1227
|
+
const rgb = parseColorRgb(hx);
|
|
1228
|
+
if (!rgb) continue;
|
|
1229
|
+
const [h, s] = rgbToHsl(rgb);
|
|
1230
|
+
if (h >= 245 && h <= 345 && s >= 45) purplePinkStops += 1;
|
|
1231
|
+
}
|
|
1232
|
+
const nearSlice = clean.slice(m.index, Math.min(clean.length, m.index + m[0].length + 120));
|
|
1233
|
+
const isClipText = /background-clip\s*:\s*text/i.test(nearSlice);
|
|
1234
|
+
if (purplePinkStops >= 2 || isClipText) {
|
|
1235
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
return hits;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function probeUiPillSoup(rawText, maxPills = 6) {
|
|
1242
|
+
const clean = rawText
|
|
1243
|
+
.replace(/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi, preserveLinesBlank)
|
|
1244
|
+
.replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
|
|
1245
|
+
.replace(/<(script|style|code|pre)\b[^>]*>[\s\S]*?<\/\1>/gi, preserveLinesBlank);
|
|
1246
|
+
|
|
1247
|
+
const pillRe = /<([a-z0-9]+)\b([^>]*(?:\brounded-full\b|border-radius\s*:\s*999\d*px)[^>]*)>([^<]{1,48})<\/\1>/gi;
|
|
1248
|
+
const matches = [];
|
|
1249
|
+
let m;
|
|
1250
|
+
while ((m = pillRe.exec(clean)) !== null) {
|
|
1251
|
+
const attrs = m[2] || "";
|
|
1252
|
+
const text = (m[3] || "").trim();
|
|
1253
|
+
if (!text) continue;
|
|
1254
|
+
// Exempt square dots/avatars (`w-6 h-6`, `size-2`)
|
|
1255
|
+
if (/\bsize-\d/.test(attrs)) continue;
|
|
1256
|
+
const wh = attrs.match(/\bw-(\d+)\b.*\bh-(\d+)\b/);
|
|
1257
|
+
if (wh && wh[1] === wh[2]) continue;
|
|
1258
|
+
matches.push({ index: m.index, length: m[0].length });
|
|
1259
|
+
}
|
|
1260
|
+
if (matches.length > maxPills) {
|
|
1261
|
+
return [matches[0]];
|
|
1262
|
+
}
|
|
1263
|
+
return [];
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
function probeUiBoxInBox(rawText) {
|
|
1267
|
+
const clean = rawText
|
|
1268
|
+
.replace(/<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi, preserveLinesBlank)
|
|
1269
|
+
.replace(/<!--[\s\S]*?-->/g, preserveLinesBlank)
|
|
1270
|
+
.replace(/<(script|style|code|pre|svg)\b[^>]*>[\s\S]*?<\/\1>/gi, preserveLinesBlank);
|
|
1271
|
+
|
|
1272
|
+
const tokenRe = /<\/?([a-zA-Z][a-zA-Z0-9-]*)\b([^>]*?)(\/?)>/g;
|
|
1273
|
+
const voidTags = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
|
1274
|
+
const stack = [];
|
|
1275
|
+
const hits = [];
|
|
1276
|
+
let m;
|
|
1277
|
+
while ((m = tokenRe.exec(clean)) !== null) {
|
|
1278
|
+
const full = m[0];
|
|
1279
|
+
const tag = m[1].toLowerCase();
|
|
1280
|
+
const attrs = m[2] || "";
|
|
1281
|
+
const selfClose = m[3] === "/" || voidTags.has(tag);
|
|
1282
|
+
if (full.startsWith("</")) {
|
|
1283
|
+
for (let i = stack.length - 1; i >= 0; i -= 1) {
|
|
1284
|
+
if (stack[i].tag === tag) {
|
|
1285
|
+
stack.length = i;
|
|
1286
|
+
break;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
continue;
|
|
1290
|
+
}
|
|
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);
|
|
1292
|
+
const hasRadius = /\brounded(?:-[a-z0-9]+)?\b|border-radius\s*:/i.test(attrs) && !/\brounded-none\b/.test(attrs);
|
|
1293
|
+
const hasPad = /\bp[xy]?-\d|padding\s*:/i.test(attrs);
|
|
1294
|
+
const isBox = hasBorderOrShadow && hasRadius && hasPad;
|
|
1295
|
+
const boxDepth = (stack.length > 0 ? stack[stack.length - 1].boxDepth : 0) + (isBox ? 1 : 0);
|
|
1296
|
+
|
|
1297
|
+
if (isBox && boxDepth >= 3 && hits.length === 0) {
|
|
1298
|
+
hits.push({ index: m.index, length: full.length });
|
|
1299
|
+
}
|
|
1300
|
+
if (!selfClose) {
|
|
1301
|
+
stack.push({ tag, boxDepth });
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
return hits;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
function normalizeAsciiDigits(str) {
|
|
1308
|
+
return String(str || "").replace(/[0-9]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0));
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function hasMultiplierBaseline(sentence) {
|
|
1312
|
+
const s = normalizeAsciiDigits(sentence);
|
|
1313
|
+
if (/\bfrom\s+\S+[\s\S]{0,36}\bto\s+\S*\d/i.test(s)) return true;
|
|
1314
|
+
if (/\b(?:vs\.?|compared\s+(?:to|with))\s+\S*\d/i.test(s)) return true;
|
|
1315
|
+
if (/(?:从|由)\s*\d[\s\S]{0,28}(?:到|至|升至|降至|压到|降到|缩短至)\s*\d/.test(s)) return true;
|
|
1316
|
+
const measured =
|
|
1317
|
+
s.match(
|
|
1318
|
+
/(?<![A-Za-z0-9_])\d[\d,.]*\s*(?:%|(?:milliseconds?|ms|minutes?|mins?|seconds?|secs?|s|hours?|hrs?|KB|MB|GB|TB|QPS|TPS|RPS)\b|秒|分钟|小时|毫秒|万|亿|元|美元)/gi
|
|
1319
|
+
) || [];
|
|
1320
|
+
return measured.length >= 2;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
function probeUnanchoredMultiplier(zoneText, rawText) {
|
|
1324
|
+
const normZone = normalizeAsciiDigits(zoneText);
|
|
1325
|
+
const hits = [];
|
|
1326
|
+
const patterns = [
|
|
1327
|
+
/\b(?:\d+(?:\.\d+)?x)\s+(?:faster|more\s+efficient|higher\s+(?:productivity|throughput|conversion)|lower\s+cost|cheaper|speedup)\b/gi,
|
|
1328
|
+
/(?:效率|性能|速度|产能|转化率|吞吐量)(?:提升|提高|加快|翻了?|暴涨)(?:了?\s*)?(?:数倍|十倍|百倍|几十倍|好几倍|\d+(?:\.\d+)?\s*倍)/g,
|
|
1329
|
+
];
|
|
1330
|
+
for (const re of patterns) {
|
|
1331
|
+
let m;
|
|
1332
|
+
while ((m = re.exec(normZone)) !== null) {
|
|
1333
|
+
const sent = enclosingSentence(rawText, m.index, m.index + m[0].length);
|
|
1334
|
+
if (hasMultiplierBaseline(sent)) continue;
|
|
1335
|
+
hits.push({ index: m.index, length: m[0].length });
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
return hits;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// ---------- Core Text Auditor ----------
|
|
1342
|
+
|
|
1343
|
+
export function auditText(text, { filename = "<memory>", modality = null, pack, config = {}, allowSyntheticFixtures = false } = {}) {
|
|
1344
|
+
const mod = modality || detectModality(filename) || "markdown";
|
|
1345
|
+
const lineStarts = buildLineStarts(text);
|
|
1346
|
+
const zones = buildZones(text, mod);
|
|
1347
|
+
const { byTargetLine, directives } = parseSuppressions(text);
|
|
1348
|
+
const allowList = config?.allow || [];
|
|
1349
|
+
const cpPrefix = /[\uD800-\uDBFF]/.test(text) ? buildCodePointPrefix(text) : null;
|
|
1350
|
+
const findings = [];
|
|
1351
|
+
|
|
1352
|
+
for (const rule of pack.rules || []) {
|
|
1353
|
+
if (rule.modalities && !rule.modalities.includes(mod)) continue;
|
|
1354
|
+
|
|
1355
|
+
// Synthetic Office/PDF fixture tokens ONLY during `dislop pack-test`
|
|
1356
|
+
if (allowSyntheticFixtures && (text.startsWith("DOCX_") || text.startsWith("PPTX_"))) {
|
|
1357
|
+
const synthHits = evaluateSyntheticBinaryFixture(text, rule, pack.thresholds || {});
|
|
1358
|
+
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 } }));
|
|
1360
|
+
}
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
let rawHits = [];
|
|
1365
|
+
const primaryZoneName = (rule.zones && rule.zones[0]) || "prose";
|
|
1366
|
+
const zoneText = zones[primaryZoneName] ?? zones.prose;
|
|
1367
|
+
|
|
1368
|
+
if (rule.probe === "regex") {
|
|
1369
|
+
for (const pattern of rule.patterns || []) {
|
|
1370
|
+
const re = new RegExp(pattern, "gimu");
|
|
1371
|
+
let m;
|
|
1372
|
+
while ((m = re.exec(zoneText)) !== null) {
|
|
1373
|
+
if (m[0].length === 0) {
|
|
1374
|
+
re.lastIndex += 1;
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
let idx = m.index;
|
|
1378
|
+
let len = m[0].length;
|
|
1379
|
+
if (primaryZoneName === "prose") {
|
|
1380
|
+
const lead = m[0].match(/^[.!?。!?\s]+/);
|
|
1381
|
+
if (lead && lead[0].length < len) {
|
|
1382
|
+
idx += lead[0].length;
|
|
1383
|
+
len -= lead[0].length;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
while (len > 1 && text.charCodeAt(idx) === 0xfeff) {
|
|
1387
|
+
idx += 1;
|
|
1388
|
+
len -= 1;
|
|
1389
|
+
}
|
|
1390
|
+
if (
|
|
1391
|
+
rule.id === "unfilled-placeholder" &&
|
|
1392
|
+
text[idx] === "[" &&
|
|
1393
|
+
text[idx + len - 1] === "]" &&
|
|
1394
|
+
/^(?:\(|\[|:)/.test(text.slice(idx + len))
|
|
1395
|
+
) {
|
|
1396
|
+
continue;
|
|
1397
|
+
}
|
|
1398
|
+
rawHits.push({ index: idx, length: len });
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
} else if (rule.probe === "negation-pivot") {
|
|
1402
|
+
rawHits = probeNegationPivot(zoneText, text);
|
|
1403
|
+
} else if (rule.probe === "staccato-run") {
|
|
1404
|
+
rawHits = probeStaccatoRun(zoneText);
|
|
1405
|
+
} else if (rule.probe === "zh-four-char-triad") {
|
|
1406
|
+
rawHits = probeZhFourCharTriad(zoneText);
|
|
1407
|
+
} else if (rule.probe === "unsourced-attribution") {
|
|
1408
|
+
rawHits = probeUnsourcedAttribution(zoneText, text);
|
|
1409
|
+
} else if (rule.probe === "bold-lead-list-wall") {
|
|
1410
|
+
rawHits = probeBoldLeadListWall(zoneText, text, pack.thresholds?.boldLeadListRun || 4);
|
|
1411
|
+
} else if (rule.probe === "em-dash-density") {
|
|
1412
|
+
rawHits = probeEmDashDensity(zoneText, pack.thresholds?.maxEmDashesPer300Words || 4);
|
|
1413
|
+
} else if (rule.probe === "zh-halfwidth-punctuation") {
|
|
1414
|
+
rawHits = probeZhHalfwidthPunctuation(zoneText);
|
|
1415
|
+
} else if (rule.probe === "cooccurrence-slop-cluster") {
|
|
1416
|
+
rawHits = probeCooccurrenceSlopCluster(zoneText, text);
|
|
1417
|
+
} else if (rule.probe === "semicolon-tricolon") {
|
|
1418
|
+
rawHits = probeSemicolonTricolon(zoneText, text);
|
|
1419
|
+
} else if (rule.probe === "rhetorical-qa-cadence") {
|
|
1420
|
+
rawHits = probeRhetoricalQaCadence(zoneText, text);
|
|
1421
|
+
} else if (rule.probe === "comma-chain-runon") {
|
|
1422
|
+
rawHits = probeCommaChainRunon(zoneText, text);
|
|
1423
|
+
} else if (rule.probe === "narrative-sandwich-frame") {
|
|
1424
|
+
rawHits = probeNarrativeSandwichFrame(zoneText, text);
|
|
1425
|
+
} else if (rule.probe === "template-skeleton-echo") {
|
|
1426
|
+
rawHits = probeTemplateSkeletonEcho(zoneText, text);
|
|
1427
|
+
} else if (rule.probe === "low-burstiness-vapor") {
|
|
1428
|
+
rawHits = probeLowBurstinessVapor(zoneText, text);
|
|
1429
|
+
} else if (rule.probe === "unanchored-multiplier") {
|
|
1430
|
+
rawHits = probeUnanchoredMultiplier(zoneText, text);
|
|
1431
|
+
} else if (rule.probe === "ui-dead-control") {
|
|
1432
|
+
rawHits = probeUiDeadControl(text);
|
|
1433
|
+
} else if (rule.probe === "ui-ai-gradient") {
|
|
1434
|
+
rawHits = probeUiAiGradient(text);
|
|
1435
|
+
} else if (rule.probe === "ui-pill-soup") {
|
|
1436
|
+
rawHits = probeUiPillSoup(text, pack.thresholds?.maxPillsPerFile || 6);
|
|
1437
|
+
} else if (rule.probe === "ui-box-in-box") {
|
|
1438
|
+
rawHits = probeUiBoxInBox(text);
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
// Sort and deduplicate overlapping spans emitted by multiple patterns of the same rule
|
|
1442
|
+
rawHits.sort((a, b) => a.index - b.index || b.length - a.length);
|
|
1443
|
+
const dedupHits = [];
|
|
1444
|
+
for (const h of rawHits) {
|
|
1445
|
+
const prev = dedupHits[dedupHits.length - 1];
|
|
1446
|
+
if (prev && h.index < prev.index + prev.length) continue;
|
|
1447
|
+
dedupHits.push(h);
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
for (const hit of dedupHits) {
|
|
1451
|
+
const start = hit.index;
|
|
1452
|
+
const end = hit.index + hit.length;
|
|
1453
|
+
const matchedRaw = text.slice(start, end);
|
|
1454
|
+
if (isAllowedMatch(matchedRaw, allowList)) continue;
|
|
1455
|
+
|
|
1456
|
+
const { line, col } = offsetToLineCol(text, lineStarts, start, cpPrefix);
|
|
1457
|
+
const lineSuppressions = byTargetLine.get(line) || [];
|
|
1458
|
+
let suppressed = false;
|
|
1459
|
+
for (const sup of lineSuppressions) {
|
|
1460
|
+
if (sup.ruleIds.includes("all") || sup.ruleIds.includes("*") || sup.ruleIds.includes(rule.id)) {
|
|
1461
|
+
sup.used = true;
|
|
1462
|
+
suppressed = true;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
if (suppressed) continue;
|
|
1466
|
+
|
|
1467
|
+
const sentence = enclosingSentence(text, start, end);
|
|
1468
|
+
const cpStart = cpPrefix ? cpPrefix[start] : start;
|
|
1469
|
+
const cpEnd = cpPrefix ? cpPrefix[end] : end;
|
|
1470
|
+
findings.push(
|
|
1471
|
+
makeFinding({
|
|
1472
|
+
rule: hit.severity ? { ...rule, severity: hit.severity } : rule,
|
|
1473
|
+
filename,
|
|
1474
|
+
modality: mod,
|
|
1475
|
+
location: `${line}:${col}`,
|
|
1476
|
+
line,
|
|
1477
|
+
col,
|
|
1478
|
+
span: { start: cpStart, end: cpEnd },
|
|
1479
|
+
match: clipCodepoints(matchedRaw.replace(/\s+/g, " ").trim(), 140),
|
|
1480
|
+
sentence,
|
|
1481
|
+
})
|
|
1482
|
+
);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const unusedSuppressions = directives
|
|
1487
|
+
.filter((d) => !d.used)
|
|
1488
|
+
.map((d) => ({
|
|
1489
|
+
file: filename,
|
|
1490
|
+
line: d.directiveLine,
|
|
1491
|
+
ruleIds: d.ruleIds,
|
|
1492
|
+
reason: d.reason,
|
|
1493
|
+
}));
|
|
1494
|
+
|
|
1495
|
+
findings.sort((a, b) => (a.line || 0) - (b.line || 0) || (a.col || 0) - (b.col || 0));
|
|
1496
|
+
return { findings, unusedSuppressions };
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
function evaluateSyntheticBinaryFixture(fixture, rule, thresholds) {
|
|
1500
|
+
if (rule.probe === "office-markdown-leak" && fixture.startsWith("DOCX_RAW_MARKDOWN:")) {
|
|
1501
|
+
return [{ location: "para 1", match: "**Key Milestone**" }];
|
|
1502
|
+
}
|
|
1503
|
+
if (rule.probe === "slide-word-wall" && fixture.startsWith("PPTX_WORD_WALL:")) {
|
|
1504
|
+
const count = Number(fixture.split(":")[1] || 0);
|
|
1505
|
+
if (count > (thresholds.maxSlideWords || 120)) return [{ location: "slide 1", match: `${count} words` }];
|
|
1506
|
+
}
|
|
1507
|
+
if (rule.probe === "slide-bullet-overload" && fixture.startsWith("PPTX_BULLETS:")) {
|
|
1508
|
+
const count = Number(fixture.split(":")[1] || 0);
|
|
1509
|
+
if (count > (thresholds.maxSlideBullets || 6)) return [{ location: "slide 1", match: `${count} bullets` }];
|
|
1510
|
+
}
|
|
1511
|
+
if (rule.probe === "slide-autofit-shrink" && fixture.startsWith("PPTX_AUTOFIT:")) {
|
|
1512
|
+
const scale = Number(fixture.split(":")[1] || 100000);
|
|
1513
|
+
if (scale < (thresholds.minAutofitScale || 80000)) return [{ location: "slide 1", match: `fontScale=${scale}` }];
|
|
1514
|
+
}
|
|
1515
|
+
if (rule.probe === "slide-weak-topic-title" && fixture.startsWith("PPTX_WEAK_TITLE:")) {
|
|
1516
|
+
return [{ location: "slide 1", match: fixture.split(":")[1] }];
|
|
1517
|
+
}
|
|
1518
|
+
if (rule.probe === "pptx-layout-monotony" && fixture.startsWith("PPTX_MONOTONY:")) {
|
|
1519
|
+
const run = Number(fixture.split(":")[1] || 0);
|
|
1520
|
+
if (run >= (thresholds.maxIdenticalSlideRun || 4)) {
|
|
1521
|
+
return [{ location: `slide ${run}`, match: `${run} consecutive identical slide layouts` }];
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return [];
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
export function makeFinding({ rule, filename, modality, location, line = 1, col = 1, span = null, match, sentence = "" }) {
|
|
1528
|
+
const normMatch = String(match || "").toLowerCase().trim();
|
|
1529
|
+
const normSent = String(sentence || normMatch).toLowerCase().replace(/\s+/g, " ").trim();
|
|
1530
|
+
const fingerprint = `${rule.id}:${fnv1aHex(`${rule.id}|${normMatch}|${normSent}`)}`;
|
|
1531
|
+
return {
|
|
1532
|
+
fingerprint,
|
|
1533
|
+
ruleId: rule.id,
|
|
1534
|
+
tier: rule.tier || "taste",
|
|
1535
|
+
severity: rule.severity || "warning",
|
|
1536
|
+
family: rule.family || "general",
|
|
1537
|
+
file: filename,
|
|
1538
|
+
modality,
|
|
1539
|
+
location,
|
|
1540
|
+
line,
|
|
1541
|
+
col,
|
|
1542
|
+
span,
|
|
1543
|
+
match,
|
|
1544
|
+
message: rule.message,
|
|
1545
|
+
deletionTest: rule.deletionTest || null,
|
|
1546
|
+
exemplar: rule.exemplar || null,
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// ---------- Structured DOCX / PPTX Document Auditor ----------
|
|
1551
|
+
|
|
1552
|
+
function decodeXmlEntities(str) {
|
|
1553
|
+
return String(str).replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|lt|gt|quot|apos|amp);/g, (m, dec, hex) => {
|
|
1554
|
+
if (dec) {
|
|
1555
|
+
const cp = Number(dec);
|
|
1556
|
+
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : m;
|
|
1557
|
+
}
|
|
1558
|
+
if (hex) {
|
|
1559
|
+
const cp = parseInt(hex, 16);
|
|
1560
|
+
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : m;
|
|
1561
|
+
}
|
|
1562
|
+
if (m === "<") return "<";
|
|
1563
|
+
if (m === ">") return ">";
|
|
1564
|
+
if (m === """) return '"';
|
|
1565
|
+
if (m === "'") return "'";
|
|
1566
|
+
return "&";
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/**
|
|
1571
|
+
* Audit an already-extracted map of archive entries `{ [entryPath]: string }` for `.docx` or `.pptx`.
|
|
1572
|
+
* Shared between Node (`zlib.inflateRawSync`) and Browser (`DecompressionStream('deflate-raw')`).
|
|
1573
|
+
*/
|
|
1574
|
+
export function auditOoxmlEntries(entries, { filename, modality, pack, config = {} }) {
|
|
1575
|
+
const findings = [];
|
|
1576
|
+
const skipped = [];
|
|
1577
|
+
const rulesById = new Map((pack.rules || []).map((r) => [r.id, r]));
|
|
1578
|
+
|
|
1579
|
+
if (modality === "docx") {
|
|
1580
|
+
const docXml = entries["word/document.xml"];
|
|
1581
|
+
if (!docXml) {
|
|
1582
|
+
return { findings, skipped: [{ file: filename, reason: "Missing word/document.xml inside DOCX archive" }] };
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
// Extract paragraphs joining <w:t> runs cleanly while excluding <w:delText>
|
|
1586
|
+
const paraRe = /<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g;
|
|
1587
|
+
let pm;
|
|
1588
|
+
let paraIndex = 0;
|
|
1589
|
+
const mdLeakRule = rulesById.get("markdown-leak");
|
|
1590
|
+
while ((pm = paraRe.exec(docXml)) !== null) {
|
|
1591
|
+
const pBody = pm[1].replace(/<w:del\b[\s\S]*?<\/w:del>/g, "");
|
|
1592
|
+
const runs = [];
|
|
1593
|
+
const tRe = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g;
|
|
1594
|
+
let tm;
|
|
1595
|
+
while ((tm = tRe.exec(pBody)) !== null) {
|
|
1596
|
+
runs.push(decodeXmlEntities(tm[1]));
|
|
1597
|
+
}
|
|
1598
|
+
const paraText = runs.join("").trim();
|
|
1599
|
+
if (!paraText) continue;
|
|
1600
|
+
paraIndex += 1;
|
|
1601
|
+
|
|
1602
|
+
if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(paraText) || /^#{1,6}\s+\S/.test(paraText))) {
|
|
1603
|
+
findings.push(makeFinding({ rule: mdLeakRule, filename, modality, location: `para ${paraIndex}`, line: paraIndex, match: paraText.slice(0, 100) }));
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
const sub = auditText(paraText, { filename, modality: "markdown", pack, config });
|
|
1607
|
+
for (const f of sub.findings) {
|
|
1608
|
+
if (f.ruleId === "markdown-leak") continue;
|
|
1609
|
+
findings.push({ ...f, modality: "docx", location: `para ${paraIndex}`, line: paraIndex });
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
return { findings, skipped };
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
if (modality === "pptx") {
|
|
1616
|
+
const presXml = entries["ppt/presentation.xml"] || "";
|
|
1617
|
+
const presRels = entries["ppt/_rels/presentation.xml.rels"] || "";
|
|
1618
|
+
|
|
1619
|
+
// Resolve presentation slide order via p:sldIdLst -> r:id -> Target
|
|
1620
|
+
const relMap = new Map();
|
|
1621
|
+
const relRe = /<Relationship\b[^>]*\bId="([^"]+)"[^>]*\bTarget="([^"]+)"|<Relationship\b[^>]*\bTarget="([^"]+)"[^>]*\bId="([^"]+)"/g;
|
|
1622
|
+
let rm;
|
|
1623
|
+
while ((rm = relRe.exec(presRels)) !== null) {
|
|
1624
|
+
const id = rm[1] || rm[4];
|
|
1625
|
+
const rawTarget = (rm[2] || rm[3] || "").replace(/^\/+/, "").replace(/^\.\.\//, "ppt/");
|
|
1626
|
+
const target = rawTarget.startsWith("ppt/") ? rawTarget : `ppt/${rawTarget}`;
|
|
1627
|
+
relMap.set(id, target);
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
const orderedSlides = [];
|
|
1631
|
+
const sldIdRe = /<p:sldId\b[^>]*\br:id="([^"]+)"/g;
|
|
1632
|
+
let sm;
|
|
1633
|
+
while ((sm = sldIdRe.exec(presXml)) !== null) {
|
|
1634
|
+
const target = relMap.get(sm[1]);
|
|
1635
|
+
if (target && entries[target]) orderedSlides.push(target);
|
|
1636
|
+
}
|
|
1637
|
+
if (orderedSlides.length === 0) {
|
|
1638
|
+
const fallback = Object.keys(entries)
|
|
1639
|
+
.filter((k) => /^ppt\/slides\/slide\d+\.xml$/.test(k))
|
|
1640
|
+
.sort((a, b) => Number(a.match(/\d+/)[0]) - Number(b.match(/\d+/)[0]));
|
|
1641
|
+
orderedSlides.push(...fallback);
|
|
1642
|
+
}
|
|
1643
|
+
if (orderedSlides.length === 0) {
|
|
1644
|
+
return { findings, skipped: [{ file: filename, reason: "Missing ppt/slides/*.xml inside PPTX archive" }] };
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
const mdLeakRule = rulesById.get("markdown-leak");
|
|
1648
|
+
const wordWallRule = rulesById.get("slide-word-wall");
|
|
1649
|
+
const bulletRule = rulesById.get("slide-bullet-overload");
|
|
1650
|
+
const autofitRule = rulesById.get("slide-autofit-shrink");
|
|
1651
|
+
const weakTitleRule = rulesById.get("slide-weak-topic-title");
|
|
1652
|
+
const processTitleRule = rulesById.get("slide-process-not-finding-title");
|
|
1653
|
+
const monotonyRule = rulesById.get("pptx-layout-monotony");
|
|
1654
|
+
const thresholds = pack.thresholds || {};
|
|
1655
|
+
let prevLayoutSig = null;
|
|
1656
|
+
let layoutRunCount = 0;
|
|
1657
|
+
|
|
1658
|
+
orderedSlides.forEach((slideEntry, idx) => {
|
|
1659
|
+
const slideNum = idx + 1;
|
|
1660
|
+
const xml = entries[slideEntry];
|
|
1661
|
+
const isHidden = /<p:sld\b[^>]*\bshow="(?:0|false)"/i.test(xml);
|
|
1662
|
+
if (isHidden) {
|
|
1663
|
+
skipped.push({ file: `${filename}#slide-${slideNum}`, reason: "Hidden slide (show=0) skipped for density rules" });
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
// Autofit shrink check
|
|
1667
|
+
if (autofitRule && !isHidden) {
|
|
1668
|
+
const afMatch = xml.match(/<a:normAutofit\b[^>]*\bfontScale="(\d+)"/);
|
|
1669
|
+
if (afMatch && Number(afMatch[1]) < (thresholds.minAutofitScale || 80000)) {
|
|
1670
|
+
const pct = Math.round(Number(afMatch[1]) / 1000);
|
|
1671
|
+
findings.push(makeFinding({ rule: autofitRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: `normAutofit fontScale=${pct}%` }));
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
// Inspect shapes (<p:sp>) for title, bullets, and joined paragraphs
|
|
1676
|
+
const spRe = /<p:sp\b[\s\S]*?<\/p:sp>/g;
|
|
1677
|
+
const slideParagraphs = [];
|
|
1678
|
+
let titleText = "";
|
|
1679
|
+
let bulletCount = 0;
|
|
1680
|
+
let nonFooterSpCount = 0;
|
|
1681
|
+
let spm;
|
|
1682
|
+
while ((spm = spRe.exec(xml)) !== null) {
|
|
1683
|
+
const sp = spm[0];
|
|
1684
|
+
const isTitle = /<p:ph\b[^>]*\btype="(?:title|ctrTitle)"/.test(sp);
|
|
1685
|
+
const isFooterOrNum = /<p:ph\b[^>]*\btype="(?:sldNum|ftr|dt)"/.test(sp);
|
|
1686
|
+
if (!isFooterOrNum) nonFooterSpCount += 1;
|
|
1687
|
+
const paras = [];
|
|
1688
|
+
const apRe = /<a:p\b[^>]*>([\s\S]*?)<\/a:p>/g;
|
|
1689
|
+
let apm;
|
|
1690
|
+
while ((apm = apRe.exec(sp)) !== null) {
|
|
1691
|
+
const pInner = apm[1];
|
|
1692
|
+
const runs = [];
|
|
1693
|
+
const atRe = /<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g;
|
|
1694
|
+
let atm;
|
|
1695
|
+
while ((atm = atRe.exec(pInner)) !== null) {
|
|
1696
|
+
runs.push(decodeXmlEntities(atm[1]));
|
|
1697
|
+
}
|
|
1698
|
+
const joined = runs.join("").trim();
|
|
1699
|
+
if (!joined) continue;
|
|
1700
|
+
paras.push(joined);
|
|
1701
|
+
if (!isTitle && !isFooterOrNum && (/<a:buChar\b|<a:buAutoNum\b/.test(pInner) || (!/<a:buNone\b/.test(pInner) && paras.length > 1))) {
|
|
1702
|
+
if (/<a:buChar\b|<a:buAutoNum\b/.test(pInner)) bulletCount += 1;
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
if (paras.length === 0) continue;
|
|
1706
|
+
if (isTitle && !titleText) titleText = paras.join(" ");
|
|
1707
|
+
if (!isFooterOrNum) slideParagraphs.push(...paras);
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
const fullSlideText = slideParagraphs.join("\n");
|
|
1711
|
+
if (mdLeakRule && (/\*\*[^*\n]{1,80}\*\*/.test(fullSlideText) || /^#{1,6}\s+\S/m.test(fullSlideText))) {
|
|
1712
|
+
findings.push(makeFinding({ rule: mdLeakRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: fullSlideText.slice(0, 90) }));
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
if (!isHidden) {
|
|
1716
|
+
const cjkChars = (fullSlideText.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
1717
|
+
const latinWords = fullSlideText.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
|
|
1718
|
+
const maxWords = thresholds.maxSlideWords || 120;
|
|
1719
|
+
const maxZh = thresholds.maxSlideCharsZh || 280;
|
|
1720
|
+
if (wordWallRule && (latinWords > maxWords || cjkChars > maxZh)) {
|
|
1721
|
+
findings.push(makeFinding({ rule: wordWallRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: `${latinWords} words / ${cjkChars} CJK chars` }));
|
|
1722
|
+
}
|
|
1723
|
+
if (bulletRule && bulletCount > (thresholds.maxSlideBullets || 6)) {
|
|
1724
|
+
findings.push(makeFinding({ rule: bulletRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: `${bulletCount} bullet items` }));
|
|
1725
|
+
}
|
|
1726
|
+
if (weakTitleRule && titleText && (latinWords > 25 || cjkChars > 50)) {
|
|
1727
|
+
if (/^(?:overview|background|agenda|summary|introduction|context|背景|项目背景|概述|数据概述|总结|目录)$/i.test(titleText.trim())) {
|
|
1728
|
+
findings.push(makeFinding({ rule: weakTitleRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: `Title: "${titleText.trim()}"` }));
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
if (processTitleRule && titleText) {
|
|
1732
|
+
const tt = titleText.trim().replace(/\s*#+\s*$/, "").trim();
|
|
1733
|
+
if (
|
|
1734
|
+
/^(?:Analysis\s+of|Overview\s+of|Update\s+on|Discussion\s+of|Deep\s+Dive\s+into|Thoughts\s+on)\s+\S[^\n#]{1,64}$/i.test(tt) ||
|
|
1735
|
+
/^(?:关于[^\n#]{2,36}的(?:分析(?:汇报|报告)?|汇报|思考|探讨|情况(?:说明|汇报)?)|[^\n#]{2,24}(?:阶段性进展汇报|情况分析汇报))$/.test(tt)
|
|
1736
|
+
) {
|
|
1737
|
+
findings.push(makeFinding({ rule: processTitleRule, filename, modality, location: `slide ${slideNum}`, line: slideNum, match: `Title: "${tt}"` }));
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
if (monotonyRule) {
|
|
1741
|
+
const hasDataGraphic = /<c:chart\b|<a:tbl\b/.test(xml);
|
|
1742
|
+
const picCount = (xml.match(/<p:pic\b/g) || []).length;
|
|
1743
|
+
const bulletBucket = bulletCount === 0 ? 0 : bulletCount <= 3 ? 1 : 2;
|
|
1744
|
+
const offs = [...xml.matchAll(/<a:off\b[^>]*\bx="(-?\d+)"[^>]*\by="(-?\d+)"/g)]
|
|
1745
|
+
.slice(0, 6)
|
|
1746
|
+
.map((m) => `${Math.round(Number(m[1]) / 914400)},${Math.round(Number(m[2]) / 914400)}`)
|
|
1747
|
+
.join(";");
|
|
1748
|
+
const geomPart = offs ? `|g:${offs}` : "";
|
|
1749
|
+
const sig =
|
|
1750
|
+
!hasDataGraphic && nonFooterSpCount >= 2 && (latinWords > 8 || cjkChars > 16)
|
|
1751
|
+
? `sp:${nonFooterSpCount}|b:${bulletBucket}|p:${picCount}${geomPart}`
|
|
1752
|
+
: null;
|
|
1753
|
+
if (sig && sig === prevLayoutSig) {
|
|
1754
|
+
layoutRunCount += 1;
|
|
1755
|
+
} else {
|
|
1756
|
+
prevLayoutSig = sig;
|
|
1757
|
+
layoutRunCount = sig ? 1 : 0;
|
|
1758
|
+
}
|
|
1759
|
+
if (layoutRunCount === (thresholds.maxIdenticalSlideRun || 4)) {
|
|
1760
|
+
findings.push(
|
|
1761
|
+
makeFinding({
|
|
1762
|
+
rule: monotonyRule,
|
|
1763
|
+
filename,
|
|
1764
|
+
modality,
|
|
1765
|
+
location: `slide ${slideNum}`,
|
|
1766
|
+
line: slideNum,
|
|
1767
|
+
match: `${layoutRunCount} consecutive identical slide layouts (${sig})`,
|
|
1768
|
+
})
|
|
1769
|
+
);
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
|
|
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 });
|
|
1776
|
+
for (const f of sub.findings) {
|
|
1777
|
+
if (isHidden && f.severity !== "error") continue;
|
|
1778
|
+
findings.push({ ...f, modality: "pptx", location: `slide ${slideNum}`, line: slideNum });
|
|
1779
|
+
}
|
|
1780
|
+
});
|
|
1781
|
+
|
|
1782
|
+
return { findings, skipped };
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
return { findings, skipped };
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
// ---------- Output Formatters (text, json, sarif, github, md) ----------
|
|
1789
|
+
|
|
1790
|
+
function escapeGithubProp(val) {
|
|
1791
|
+
return String(val ?? "")
|
|
1792
|
+
.replace(/%/g, "%25")
|
|
1793
|
+
.replace(/\r/g, "%0D")
|
|
1794
|
+
.replace(/\n/g, "%0A")
|
|
1795
|
+
.replace(/:/g, "%3A")
|
|
1796
|
+
.replace(/,/g, "%2C");
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
function escapeGithubData(val) {
|
|
1800
|
+
return String(val ?? "")
|
|
1801
|
+
.replace(/%/g, "%25")
|
|
1802
|
+
.replace(/\r/g, "%0D")
|
|
1803
|
+
.replace(/\n/g, "%0A");
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
export function formatReport(report, format = "text", lang = "en") {
|
|
1807
|
+
const { findings, checkedCount, skipped = [], unusedSuppressions = [] } = report;
|
|
1808
|
+
if (format === "json") {
|
|
1809
|
+
return JSON.stringify(report, null, 2);
|
|
1810
|
+
}
|
|
1811
|
+
if (format === "sarif") {
|
|
1812
|
+
return JSON.stringify(buildSarif(report, lang), null, 2);
|
|
1813
|
+
}
|
|
1814
|
+
if (format === "github") {
|
|
1815
|
+
const lines = findings.map((f) => {
|
|
1816
|
+
const level = f.severity === "error" ? "error" : f.severity === "warning" ? "warning" : "notice";
|
|
1817
|
+
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})`)}`;
|
|
1819
|
+
});
|
|
1820
|
+
return lines.join("\n");
|
|
1821
|
+
}
|
|
1822
|
+
if (format === "md") {
|
|
1823
|
+
const rows = [
|
|
1824
|
+
`| Severity | File | Location | Rule | Match | Guidance |`,
|
|
1825
|
+
`|---|---|---|---|---|---|`,
|
|
1826
|
+
...findings.map(
|
|
1827
|
+
(f) =>
|
|
1828
|
+
`| \`${f.severity}\` | \`${f.file}\` | \`${f.location}\` | \`${f.ruleId}\` | \`${String(f.match).replace(/\|/g, "\\|")}\` | ${f.message?.[lang] || f.message?.en || ""} |`
|
|
1829
|
+
),
|
|
1830
|
+
];
|
|
1831
|
+
return rows.join("\n");
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
// Default human text format
|
|
1835
|
+
const out = [];
|
|
1836
|
+
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
|
+
);
|
|
1843
|
+
} 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}`);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
for (const u of unusedSuppressions) {
|
|
1855
|
+
out.push(` [UNUSED] ${u.file}:${u.line} stale dislop-ignore (${u.ruleIds.join(", ")})`);
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
for (const s of skipped) {
|
|
1859
|
+
out.push(` [SKIP] ${s.file} — ${s.reason}`);
|
|
1860
|
+
}
|
|
1861
|
+
if (report.profiles && report.profiles.length > 0) {
|
|
1862
|
+
for (const item of report.profiles) {
|
|
1863
|
+
const p = item.profile;
|
|
1864
|
+
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
|
+
);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
return out.join("\n");
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
function buildSarif(report, lang = "en") {
|
|
1874
|
+
const rulesMap = new Map();
|
|
1875
|
+
for (const f of report.findings) {
|
|
1876
|
+
if (!rulesMap.has(f.ruleId)) {
|
|
1877
|
+
rulesMap.set(f.ruleId, {
|
|
1878
|
+
id: f.ruleId,
|
|
1879
|
+
shortDescription: { text: f.message?.[lang] || f.message?.en || f.ruleId },
|
|
1880
|
+
help: {
|
|
1881
|
+
text: f.deletionTest?.[lang] || f.deletionTest?.en || f.message?.en || f.ruleId,
|
|
1882
|
+
},
|
|
1883
|
+
helpUri: `https://dislop.com/#rule-${f.ruleId}`,
|
|
1884
|
+
defaultConfiguration: {
|
|
1885
|
+
level: f.severity === "error" ? "error" : f.severity === "warning" ? "warning" : "note",
|
|
1886
|
+
},
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
return {
|
|
1891
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
1892
|
+
version: "2.1.0",
|
|
1893
|
+
runs: [
|
|
1894
|
+
{
|
|
1895
|
+
tool: {
|
|
1896
|
+
driver: {
|
|
1897
|
+
name: "dislop",
|
|
1898
|
+
version: ENGINE_VERSION,
|
|
1899
|
+
informationUri: "https://dislop.com",
|
|
1900
|
+
rules: Array.from(rulesMap.values()),
|
|
1901
|
+
},
|
|
1902
|
+
},
|
|
1903
|
+
results: report.findings.map((f) => ({
|
|
1904
|
+
ruleId: f.ruleId,
|
|
1905
|
+
level: f.severity === "error" ? "error" : f.severity === "warning" ? "warning" : "note",
|
|
1906
|
+
message: {
|
|
1907
|
+
text: `${f.message?.[lang] || f.message?.en} — "${f.match}"`,
|
|
1908
|
+
},
|
|
1909
|
+
locations: [
|
|
1910
|
+
{
|
|
1911
|
+
physicalLocation: {
|
|
1912
|
+
artifactLocation: { uri: String(f.file).replace(/^\.\//, "") },
|
|
1913
|
+
region: {
|
|
1914
|
+
startLine: Math.max(1, f.line || 1),
|
|
1915
|
+
startColumn: Math.max(1, f.col || 1),
|
|
1916
|
+
},
|
|
1917
|
+
},
|
|
1918
|
+
},
|
|
1919
|
+
],
|
|
1920
|
+
partialFingerprints: {
|
|
1921
|
+
primaryLocationLineHash: f.fingerprint,
|
|
1922
|
+
},
|
|
1923
|
+
})),
|
|
1924
|
+
},
|
|
1925
|
+
],
|
|
1926
|
+
};
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
// ---------- Anti-Pattern Catalog & Query Engine (dislop.catalog/1) ----------
|
|
1930
|
+
|
|
1931
|
+
export const FAMILY_TO_CATEGORY = {
|
|
1932
|
+
"hygiene/": "delivery-hygiene",
|
|
1933
|
+
"office/": "office-structure",
|
|
1934
|
+
"lexicon/": "language-lexicon",
|
|
1935
|
+
"frame/": "language-template",
|
|
1936
|
+
"rhythm/": "language-rhythm",
|
|
1937
|
+
"punctuation/": "language-punctuation",
|
|
1938
|
+
"structure/": "discourse-structure",
|
|
1939
|
+
"statistics/": "statistical-rhythm",
|
|
1940
|
+
"evidence/": "evidence-rigor",
|
|
1941
|
+
"deck/": "deck-layout",
|
|
1942
|
+
"ui/": "ui-design",
|
|
1943
|
+
"composite/": "composite-signal",
|
|
1944
|
+
};
|
|
1945
|
+
|
|
1946
|
+
export function inferRuleCategory(family = "") {
|
|
1947
|
+
for (const [prefix, cat] of Object.entries(FAMILY_TO_CATEGORY)) {
|
|
1948
|
+
if (String(family).startsWith(prefix)) return cat;
|
|
1949
|
+
}
|
|
1950
|
+
return "general";
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
export function inferRuleLanguages(ruleId = "") {
|
|
1954
|
+
const id = String(ruleId);
|
|
1955
|
+
if (id.startsWith("zh-")) return ["zh"];
|
|
1956
|
+
if (id.startsWith("en-")) return ["en"];
|
|
1957
|
+
return ["en", "zh"];
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
export function buildCatalog(packsById, patternByRuleId = null) {
|
|
1961
|
+
const orderedPackIds = Object.keys(packsById).sort((a, b) => {
|
|
1962
|
+
const order = [
|
|
1963
|
+
"core",
|
|
1964
|
+
"business-brief",
|
|
1965
|
+
"engineering-spec",
|
|
1966
|
+
"regulated-comms",
|
|
1967
|
+
"literary-essay",
|
|
1968
|
+
"deck-and-ui",
|
|
1969
|
+
"executive-deck",
|
|
1970
|
+
];
|
|
1971
|
+
const ia = order.indexOf(a);
|
|
1972
|
+
const ib = order.indexOf(b);
|
|
1973
|
+
if (ia !== -1 && ib !== -1) return ia - ib;
|
|
1974
|
+
if (ia !== -1) return -1;
|
|
1975
|
+
if (ib !== -1) return 1;
|
|
1976
|
+
return a.localeCompare(b);
|
|
1977
|
+
});
|
|
1978
|
+
|
|
1979
|
+
const entries = [];
|
|
1980
|
+
const seenRuleIds = new Set();
|
|
1981
|
+
for (const pid of orderedPackIds) {
|
|
1982
|
+
const pack = packsById[pid];
|
|
1983
|
+
if (!pack) continue;
|
|
1984
|
+
for (const rule of pack.rules || []) {
|
|
1985
|
+
seenRuleIds.add(rule.id);
|
|
1986
|
+
const pat = patternByRuleId && patternByRuleId[rule.id] ? patternByRuleId[rule.id] : null;
|
|
1987
|
+
const category = rule.category || pat?.category || inferRuleCategory(rule.family || "");
|
|
1988
|
+
const languages = rule.languages || pat?.languages || inferRuleLanguages(rule.id);
|
|
1989
|
+
const tags = Array.from(new Set([...(rule.tags || []), ...(pat?.tags || [])]));
|
|
1990
|
+
const evidenceLevel = rule.evidenceLevel || pat?.evidenceLevel || (rule.tier === "invariant" ? "objective-invariant" : "editorial-consensus");
|
|
1991
|
+
entries.push({
|
|
1992
|
+
id: rule.id,
|
|
1993
|
+
packId: pack.id,
|
|
1994
|
+
tier: rule.tier || pack.tier || "taste",
|
|
1995
|
+
severity: rule.severity || "warning",
|
|
1996
|
+
family: rule.family || "general",
|
|
1997
|
+
category,
|
|
1998
|
+
dimension: pat?.dimension || null,
|
|
1999
|
+
detectionAngle: pat?.detectionAngle || rule.probe || "regex",
|
|
2000
|
+
languages,
|
|
2001
|
+
tags,
|
|
2002
|
+
evidenceLevel,
|
|
2003
|
+
modelTendencies: rule.modelTendencies || pat?.modelTendencies || [],
|
|
2004
|
+
probe: rule.probe || "regex",
|
|
2005
|
+
modalities: rule.modalities || pack.modalities || [],
|
|
2006
|
+
message: rule.message || { en: "", zh: "" },
|
|
2007
|
+
deletionTest: rule.deletionTest || null,
|
|
2008
|
+
exemplar: rule.exemplar || null,
|
|
2009
|
+
anchorUrl: `https://dislop.com/#rule-${rule.id}`,
|
|
2010
|
+
});
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
if (patternByRuleId) {
|
|
2014
|
+
for (const rid of Object.keys(patternByRuleId).sort()) {
|
|
2015
|
+
if (seenRuleIds.has(rid)) continue;
|
|
2016
|
+
const pat = patternByRuleId[rid];
|
|
2017
|
+
if (!pat || pat.status !== "active-bank") continue;
|
|
2018
|
+
const guardsText = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
|
|
2019
|
+
entries.push({
|
|
2020
|
+
id: rid,
|
|
2021
|
+
packId: pat.packId || "pattern-bank",
|
|
2022
|
+
tier: "taste",
|
|
2023
|
+
severity: pat.severityDefault || "info",
|
|
2024
|
+
family: pat.dimension ? `${pat.dimension}/${rid}` : "pattern-bank",
|
|
2025
|
+
category: pat.category || "general",
|
|
2026
|
+
dimension: pat.dimension || null,
|
|
2027
|
+
detectionAngle: pat.detectionAngle || "pattern-bank",
|
|
2028
|
+
languages: pat.languages || inferRuleLanguages(rid),
|
|
2029
|
+
tags: [...(pat.tags || [])],
|
|
2030
|
+
evidenceLevel: pat.evidenceLevel || "empirical-corpus",
|
|
2031
|
+
modelTendencies: pat.modelTendencies || [],
|
|
2032
|
+
probe: pat.detectionAngle || "pattern-bank",
|
|
2033
|
+
modalities: pat.modalities || ["markdown", "text"],
|
|
2034
|
+
message: pat.mechanism || pat.name || { en: "", zh: "" },
|
|
2035
|
+
deletionTest: guardsText ? { en: guardsText, zh: guardsText } : null,
|
|
2036
|
+
exemplar: pat.exemplar || null,
|
|
2037
|
+
anchorUrl: `https://dislop.com/patterns/#${rid}`,
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
return entries;
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
export function queryCatalog(entries, filters = {}) {
|
|
2045
|
+
const q = String(filters.query || "").trim().toLowerCase();
|
|
2046
|
+
const terms = q ? q.split(/\s+/).filter(Boolean) : [];
|
|
2047
|
+
const includeExemplars = filters.includeExemplars !== false;
|
|
2048
|
+
const limit = Number.isInteger(filters.limit) && filters.limit > 0 ? filters.limit : null;
|
|
2049
|
+
|
|
2050
|
+
const matched = entries.filter((e) => {
|
|
2051
|
+
if (filters.pack && e.packId !== filters.pack) return false;
|
|
2052
|
+
if (filters.tier && e.tier !== filters.tier) return false;
|
|
2053
|
+
if (filters.severity && e.severity !== filters.severity) return false;
|
|
2054
|
+
if (filters.category && e.category !== filters.category) return false;
|
|
2055
|
+
if (filters.dimension && e.dimension !== filters.dimension) return false;
|
|
2056
|
+
if (filters.family && !String(e.family).toLowerCase().startsWith(String(filters.family).toLowerCase())) return false;
|
|
2057
|
+
if (filters.modality && !(e.modalities || []).includes(filters.modality)) return false;
|
|
2058
|
+
if (terms.length > 0) {
|
|
2059
|
+
const haystack = [
|
|
2060
|
+
e.id,
|
|
2061
|
+
e.packId,
|
|
2062
|
+
e.family,
|
|
2063
|
+
e.category,
|
|
2064
|
+
e.dimension || "",
|
|
2065
|
+
e.detectionAngle || "",
|
|
2066
|
+
(e.tags || []).join(" "),
|
|
2067
|
+
e.message?.en || "",
|
|
2068
|
+
e.message?.zh || "",
|
|
2069
|
+
e.deletionTest?.en || "",
|
|
2070
|
+
e.deletionTest?.zh || "",
|
|
2071
|
+
e.exemplar?.bad || "",
|
|
2072
|
+
e.exemplar?.trap || "",
|
|
2073
|
+
e.exemplar?.good || "",
|
|
2074
|
+
]
|
|
2075
|
+
.join("\n")
|
|
2076
|
+
.toLowerCase();
|
|
2077
|
+
if (!terms.every((t) => haystack.includes(t))) return false;
|
|
2078
|
+
}
|
|
2079
|
+
return true;
|
|
2080
|
+
});
|
|
2081
|
+
|
|
2082
|
+
const facets = { pack: {}, category: {}, severity: {} };
|
|
2083
|
+
for (const item of matched) {
|
|
2084
|
+
facets.pack[item.packId] = (facets.pack[item.packId] || 0) + 1;
|
|
2085
|
+
facets.category[item.category] = (facets.category[item.category] || 0) + 1;
|
|
2086
|
+
facets.severity[item.severity] = (facets.severity[item.severity] || 0) + 1;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
const sliced = limit ? matched.slice(0, limit) : matched;
|
|
2090
|
+
const items = includeExemplars
|
|
2091
|
+
? sliced
|
|
2092
|
+
: sliced.map(({ exemplar, ...rest }) => rest);
|
|
2093
|
+
|
|
2094
|
+
return {
|
|
2095
|
+
schema: "dislop.catalog/1",
|
|
2096
|
+
total: entries.length,
|
|
2097
|
+
matched: matched.length,
|
|
2098
|
+
facets,
|
|
2099
|
+
items,
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
// ---------- Zero-Entropy Fact-Lock Ledger (`dislop.fact-ledger/1`) & Stet Spans ----------
|
|
2104
|
+
|
|
2105
|
+
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 },
|
|
2107
|
+
{ group: "max_lt", re: /^(?:under|below|less\s+than|fewer\s+than|<)\s*/i },
|
|
2108
|
+
{ group: "max_inc", re: /^(?:最多|不超过|不高于|至多|以内|上限(?:为)?)\s*/ },
|
|
2109
|
+
{ 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
|
+
{ group: "min_gt", re: /^(?:more\s+than|greater\s+than|over|above|>)\s*/i },
|
|
2112
|
+
{ group: "min_inc", re: /^(?:至少|不少于|不低于|下限(?:为)?)\s*/ },
|
|
2113
|
+
{ group: "min_gt", re: /^(?:超过|高于|大于)\s*/ },
|
|
2114
|
+
{ group: "approx", re: /^(?:approx(?:imately)?\.?|roughly|about|around|~|≈)\s*/i },
|
|
2115
|
+
{ group: "approx", re: /^(?:约|大约|近)\s*/ },
|
|
2116
|
+
{ group: "asof", re: /^(?:as\s+of|since|until)\s+/i },
|
|
2117
|
+
{ group: "asof", re: /^(?:截至|截止到?)\s*/ },
|
|
2118
|
+
];
|
|
2119
|
+
|
|
2120
|
+
const FACT_SUFFIX_QUALIFIERS = [
|
|
2121
|
+
{ group: "max_inc", re: /^\s*(?:以内|以下|上限)/ },
|
|
2122
|
+
{ group: "min_inc", re: /^\s*(?:以上|起)/ },
|
|
2123
|
+
{ group: "approx", re: /^\s*(?:左右)/ },
|
|
2124
|
+
];
|
|
2125
|
+
|
|
2126
|
+
const UNIT_CANON_MAP = {
|
|
2127
|
+
ms: "ms",
|
|
2128
|
+
millisecond: "ms",
|
|
2129
|
+
milliseconds: "ms",
|
|
2130
|
+
毫秒: "ms",
|
|
2131
|
+
s: "s",
|
|
2132
|
+
sec: "s",
|
|
2133
|
+
secs: "s",
|
|
2134
|
+
second: "s",
|
|
2135
|
+
seconds: "s",
|
|
2136
|
+
秒: "s",
|
|
2137
|
+
min: "min",
|
|
2138
|
+
mins: "min",
|
|
2139
|
+
minute: "min",
|
|
2140
|
+
minutes: "min",
|
|
2141
|
+
分钟: "min",
|
|
2142
|
+
hr: "h",
|
|
2143
|
+
hrs: "h",
|
|
2144
|
+
hour: "h",
|
|
2145
|
+
hours: "h",
|
|
2146
|
+
小时: "h",
|
|
2147
|
+
day: "d",
|
|
2148
|
+
days: "d",
|
|
2149
|
+
天: "d",
|
|
2150
|
+
month: "mo",
|
|
2151
|
+
months: "mo",
|
|
2152
|
+
个月: "mo",
|
|
2153
|
+
year: "yr",
|
|
2154
|
+
years: "yr",
|
|
2155
|
+
年: "yr",
|
|
2156
|
+
row: "row",
|
|
2157
|
+
rows: "row",
|
|
2158
|
+
行: "row",
|
|
2159
|
+
美元: "$",
|
|
2160
|
+
元: "cny",
|
|
2161
|
+
};
|
|
2162
|
+
|
|
2163
|
+
function canonicalizeNumericToken(token) {
|
|
2164
|
+
const clean = token.replace(/,/g, "").trim();
|
|
2165
|
+
if (/^[+-]?v\d+(?:\.\d+){1,3}$/i.test(clean)) {
|
|
2166
|
+
return clean.toLowerCase();
|
|
2167
|
+
}
|
|
2168
|
+
if (/^(?:Q[1-4]|P(?:50|90|95|99))$/i.test(clean)) {
|
|
2169
|
+
return clean.toUpperCase();
|
|
2170
|
+
}
|
|
2171
|
+
let sign = "";
|
|
2172
|
+
let rest = clean;
|
|
2173
|
+
if (rest.startsWith("+") || rest.startsWith("-")) {
|
|
2174
|
+
sign = rest[0];
|
|
2175
|
+
rest = rest.slice(1).trim();
|
|
2176
|
+
}
|
|
2177
|
+
let curr = "";
|
|
2178
|
+
if (/^[$€¥£]/.test(rest)) {
|
|
2179
|
+
curr = rest[0] === "¥" ? "cny" : rest[0];
|
|
2180
|
+
rest = rest.slice(1).trim();
|
|
2181
|
+
}
|
|
2182
|
+
const nm = rest.match(/^(\d+(?:\.\d+)?)\s*(.*)$/);
|
|
2183
|
+
if (!nm) return `${sign}${curr}${rest.toLowerCase()}`;
|
|
2184
|
+
const numPart = nm[1];
|
|
2185
|
+
const rawUnit = nm[2].trim();
|
|
2186
|
+
const normUnit = rawUnit ? UNIT_CANON_MAP[rawUnit.toLowerCase()] || UNIT_CANON_MAP[rawUnit] || rawUnit.toLowerCase() : "";
|
|
2187
|
+
return `${sign}${curr}${numPart}${normUnit}`;
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
function blankMarkupForFactScan(raw, modality) {
|
|
2191
|
+
let s = String(raw || "");
|
|
2192
|
+
s = s.replace(/```[\s\S]*?```/g, (m) => " ".repeat(m.length));
|
|
2193
|
+
if (modality === "css") return " ".repeat(s.length);
|
|
2194
|
+
if (modality === "html" || modality === "jsx" || modality === "svg" || /<[a-zA-Z][^>]*>/.test(s)) {
|
|
2195
|
+
s = s.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, (m) => " ".repeat(m.length));
|
|
2196
|
+
s = s.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, (m) => " ".repeat(m.length));
|
|
2197
|
+
s = s.replace(/<[^>]+>/g, (m) => " ".repeat(m.length));
|
|
2198
|
+
}
|
|
2199
|
+
return s;
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
export function extractProtectedFacts(text, { modality = "markdown" } = {}) {
|
|
2203
|
+
const raw = String(text || "");
|
|
2204
|
+
if (!raw.trim() || modality === "css") return [];
|
|
2205
|
+
const lineStarts = buildLineStarts(raw);
|
|
2206
|
+
const items = [];
|
|
2207
|
+
const occupied = [];
|
|
2208
|
+
|
|
2209
|
+
const overlaps = (start, end) => occupied.some(([a, b]) => start < b && end > a);
|
|
2210
|
+
const claim = (item) => {
|
|
2211
|
+
if (overlaps(item.span.start, item.span.end)) return;
|
|
2212
|
+
occupied.push([item.span.start, item.span.end]);
|
|
2213
|
+
const { line, col } = offsetToLineCol(raw, lineStarts, item.span.start);
|
|
2214
|
+
items.push({ ...item, line, col });
|
|
2215
|
+
};
|
|
2216
|
+
|
|
2217
|
+
const withoutFences = raw.replace(/```[\s\S]*?```/g, (m) => " ".repeat(m.length));
|
|
2218
|
+
|
|
2219
|
+
// 1. Inline code spans
|
|
2220
|
+
const codeRe = /`([^`\n]{2,80})`/g;
|
|
2221
|
+
let m;
|
|
2222
|
+
while ((m = codeRe.exec(withoutFences)) !== null) {
|
|
2223
|
+
const inner = m[1].trim();
|
|
2224
|
+
if (!inner) continue;
|
|
2225
|
+
claim({
|
|
2226
|
+
kind: "code",
|
|
2227
|
+
raw: m[0],
|
|
2228
|
+
canonical: inner,
|
|
2229
|
+
qualifier: null,
|
|
2230
|
+
span: { start: m.index, end: m.index + m[0].length },
|
|
2231
|
+
});
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
// 2. Explicit URLs and real HTML hrefs
|
|
2235
|
+
const urlRe = /\bhttps?:\/\/[^\s)>\]"']+/gi;
|
|
2236
|
+
while ((m = urlRe.exec(withoutFences)) !== null) {
|
|
2237
|
+
const cleaned = m[0].replace(/[.,;!?。,;!?]+$/, "");
|
|
2238
|
+
claim({
|
|
2239
|
+
kind: "url",
|
|
2240
|
+
raw: cleaned,
|
|
2241
|
+
canonical: cleaned,
|
|
2242
|
+
qualifier: null,
|
|
2243
|
+
span: { start: m.index, end: m.index + cleaned.length },
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
if (modality === "html" || modality === "jsx") {
|
|
2247
|
+
const hrefRe = /\bhref=["']([^"'#\s][^"']*?)["']/gi;
|
|
2248
|
+
while ((m = hrefRe.exec(raw)) !== null) {
|
|
2249
|
+
const target = m[1].trim();
|
|
2250
|
+
if (/^javascript:/i.test(target)) continue;
|
|
2251
|
+
const valStart = m.index + m[0].indexOf(target);
|
|
2252
|
+
claim({
|
|
2253
|
+
kind: "url",
|
|
2254
|
+
raw: target,
|
|
2255
|
+
canonical: target,
|
|
2256
|
+
qualifier: null,
|
|
2257
|
+
span: { start: valStart, end: valStart + target.length },
|
|
2258
|
+
});
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
|
|
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] = " ";
|
|
2267
|
+
}
|
|
2268
|
+
const cleanScan = chars.join("");
|
|
2269
|
+
|
|
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;
|
|
2271
|
+
|
|
2272
|
+
while ((m = numRe.exec(cleanScan)) !== null) {
|
|
2273
|
+
const numStart = m.index;
|
|
2274
|
+
const numEnd = m.index + m[0].length;
|
|
2275
|
+
const token = m[0].trim();
|
|
2276
|
+
|
|
2277
|
+
// Ignore numbered list markers like `1. ` or `2) ` strictly at the start of a line
|
|
2278
|
+
const lineStartIdx = cleanScan.lastIndexOf("\n", numStart - 1) + 1;
|
|
2279
|
+
const isLineLead = cleanScan.slice(lineStartIdx, numStart).trim() === "";
|
|
2280
|
+
const afterSlice = cleanScan.slice(numEnd, numEnd + 2);
|
|
2281
|
+
if (isLineLead && /^\d+$/.test(token) && /^[.)、](?:\s|$)/.test(afterSlice)) {
|
|
2282
|
+
continue;
|
|
2283
|
+
}
|
|
2284
|
+
|
|
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
|
+
}
|
|
2315
|
+
|
|
2316
|
+
const canonical = canonicalizeNumericToken(token);
|
|
2317
|
+
|
|
2318
|
+
claim({
|
|
2319
|
+
kind: qualifier ? "qualified-number" : "number",
|
|
2320
|
+
raw: raw.slice(spanStart, spanEnd).trim(),
|
|
2321
|
+
canonical,
|
|
2322
|
+
qualifier,
|
|
2323
|
+
span: { start: spanStart, end: spanEnd },
|
|
2324
|
+
});
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
items.sort((a, b) => a.span.start - b.span.start);
|
|
2328
|
+
return items;
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
export function verifyRevision(beforeText, afterText, { modality = "markdown", allowAdded = false } = {}) {
|
|
2332
|
+
const beforeFacts = extractProtectedFacts(beforeText, { modality });
|
|
2333
|
+
const afterFacts = extractProtectedFacts(afterText, { modality });
|
|
2334
|
+
const pool = afterFacts.map((f) => ({ ...f, used: false }));
|
|
2335
|
+
const preserved = [];
|
|
2336
|
+
const missing = [];
|
|
2337
|
+
const qualifierDropped = [];
|
|
2338
|
+
|
|
2339
|
+
for (const bf of beforeFacts) {
|
|
2340
|
+
const isNum = bf.kind === "number" || bf.kind === "qualified-number";
|
|
2341
|
+
const matchIdx = pool.findIndex(
|
|
2342
|
+
(af) =>
|
|
2343
|
+
!af.used &&
|
|
2344
|
+
(isNum ? af.kind === "number" || af.kind === "qualified-number" : af.kind === bf.kind) &&
|
|
2345
|
+
af.canonical === bf.canonical &&
|
|
2346
|
+
(!bf.qualifier || af.qualifier === bf.qualifier)
|
|
2347
|
+
);
|
|
2348
|
+
if (matchIdx !== -1) {
|
|
2349
|
+
pool[matchIdx].used = true;
|
|
2350
|
+
preserved.push({
|
|
2351
|
+
before: bf.raw,
|
|
2352
|
+
after: pool[matchIdx].raw,
|
|
2353
|
+
kind: bf.kind,
|
|
2354
|
+
canonical: bf.canonical,
|
|
2355
|
+
qualifier: bf.qualifier,
|
|
2356
|
+
});
|
|
2357
|
+
continue;
|
|
2358
|
+
}
|
|
2359
|
+
|
|
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
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
missing.push({
|
|
2381
|
+
raw: bf.raw,
|
|
2382
|
+
kind: bf.kind,
|
|
2383
|
+
canonical: bf.canonical,
|
|
2384
|
+
qualifier: bf.qualifier,
|
|
2385
|
+
line: bf.line,
|
|
2386
|
+
col: bf.col,
|
|
2387
|
+
});
|
|
2388
|
+
}
|
|
2389
|
+
|
|
2390
|
+
const addedNumbers = pool
|
|
2391
|
+
.filter((af) => !af.used && (af.kind === "number" || af.kind === "qualified-number"))
|
|
2392
|
+
.map((af) => ({ raw: af.raw, canonical: af.canonical, line: af.line, col: af.col }));
|
|
2393
|
+
|
|
2394
|
+
const hasDrift = missing.length > 0 || qualifierDropped.length > 0 || (!allowAdded && addedNumbers.length > 0);
|
|
2395
|
+
return {
|
|
2396
|
+
schema: "dislop.fact-ledger/1",
|
|
2397
|
+
status: hasDrift ? "drifted" : "preserved",
|
|
2398
|
+
totalProtected: beforeFacts.length,
|
|
2399
|
+
retainedCount: preserved.length,
|
|
2400
|
+
retentionRate: beforeFacts.length === 0 ? 1 : Number((preserved.length / beforeFacts.length).toFixed(4)),
|
|
2401
|
+
preserved,
|
|
2402
|
+
missing,
|
|
2403
|
+
qualifierDropped,
|
|
2404
|
+
addedNumbers,
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
// ---------- Offline Deterministic Voice Profile (`dislop.voice/1`) ----------
|
|
2409
|
+
|
|
2410
|
+
function roundHalfUp1(v) {
|
|
2411
|
+
return Math.floor(Number(v) * 10 + 0.5) / 10;
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
export function extractVoiceProfileOffline(samples, { lang = "auto" } = {}) {
|
|
2415
|
+
const cleanSamples = (Array.isArray(samples) ? samples : [samples])
|
|
2416
|
+
.map((s) => String(s || "").trim())
|
|
2417
|
+
.filter(Boolean);
|
|
2418
|
+
const combined = cleanSamples.join("\n\n");
|
|
2419
|
+
const cjkCount = (combined.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
2420
|
+
const latinWords = (combined.match(/[A-Za-z]{2,}/g) || []).length;
|
|
2421
|
+
const resolvedLang = lang === "zh" || lang === "en" ? lang : cjkCount >= latinWords ? "zh" : "en";
|
|
2422
|
+
|
|
2423
|
+
const prof = analyzeTextProfile(combined, { modality: "markdown" });
|
|
2424
|
+
const meanLen = prof.burstiness.meanLength;
|
|
2425
|
+
const cv = prof.burstiness.cv;
|
|
2426
|
+
const conc = prof.concreteness.per100Units;
|
|
2427
|
+
const emDash = prof.punctuation.emDashPer300;
|
|
2428
|
+
const minBand = roundHalfUp1(Math.max(4, meanLen * 0.65));
|
|
2429
|
+
const maxBand = roundHalfUp1(Math.max(minBand + 6, meanLen * 1.45));
|
|
2430
|
+
|
|
2431
|
+
let tone;
|
|
2432
|
+
const sentenceHabits = [];
|
|
2433
|
+
const preferredPatterns = [];
|
|
2434
|
+
const avoidPatterns = [];
|
|
2435
|
+
|
|
2436
|
+
if (resolvedLang === "zh") {
|
|
2437
|
+
tone =
|
|
2438
|
+
conc >= 4
|
|
2439
|
+
? "直接、重实据的平实技术/工作表达,优先给数字与具体对象"
|
|
2440
|
+
: "克制、自然的白话叙述,少修饰词与铺垫帽";
|
|
2441
|
+
sentenceHabits.push(
|
|
2442
|
+
cv >= 0.35
|
|
2443
|
+
? `长短句自然错落(平均句长 ${meanLen},起伏系数 ${cv})`
|
|
2444
|
+
: `句幅平稳克制(目标句长区间 ${minBand}–${maxBand})`
|
|
2445
|
+
);
|
|
2446
|
+
sentenceHabits.push(
|
|
2447
|
+
emDash <= 1
|
|
2448
|
+
? "几乎不用破折号插话,靠逗号与句号自然断句"
|
|
2449
|
+
: `适度使用破折号补充限定(约 ${emDash}/300 词单元)`
|
|
2450
|
+
);
|
|
2451
|
+
preferredPatterns.push(
|
|
2452
|
+
conc >= 3 ? "每段保留可核对的数字、时间或配置锚点" : "第一句直接交代动作主体与结论",
|
|
2453
|
+
"条件与数字紧贴写出,不拆成排比口号"
|
|
2454
|
+
);
|
|
2455
|
+
avoidPatterns.push("开头寒暄与宏大时代背景铺垫", "“不是 A,而是 B”反转与三段对称分号句");
|
|
2456
|
+
} else {
|
|
2457
|
+
tone =
|
|
2458
|
+
conc >= 4
|
|
2459
|
+
? "Direct, evidence-dense maker prose grounded in numbers and concrete nouns"
|
|
2460
|
+
: "Plain, conversational prose with minimal throat-clearing or hype";
|
|
2461
|
+
sentenceHabits.push(
|
|
2462
|
+
cv >= 0.35
|
|
2463
|
+
? `Varied sentence cadence (mean ${meanLen} units, CV ${cv})`
|
|
2464
|
+
: `Steady sentence cadence (target band ${minBand}–${maxBand} units)`
|
|
2465
|
+
);
|
|
2466
|
+
sentenceHabits.push(
|
|
2467
|
+
emDash <= 1
|
|
2468
|
+
? "Minimal em-dash interruptions; relies on periods and plain clauses"
|
|
2469
|
+
: `Moderate parenthetical em-dashes (~${emDash} per 300 units)`
|
|
2470
|
+
);
|
|
2471
|
+
preferredPatterns.push(
|
|
2472
|
+
conc >= 3 ? "Anchor claims with specific metrics, versions, or file paths" : "Lead paragraphs with concrete subjects and active verbs",
|
|
2473
|
+
"Keep bounding qualifiers ('up to', 'at least') attached to numbers"
|
|
2474
|
+
);
|
|
2475
|
+
avoidPatterns.push("Throat-clearing openers and 'Looking ahead' closers", "'Not X, but Y' pivots and 3-part semicolon pitches");
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
return {
|
|
2479
|
+
schema: "dislop.voice/1",
|
|
2480
|
+
mode: "offline-deterministic",
|
|
2481
|
+
lang: resolvedLang,
|
|
2482
|
+
stylometrics: {
|
|
2483
|
+
sampleCount: cleanSamples.length,
|
|
2484
|
+
sentenceCount: prof.sentenceCount,
|
|
2485
|
+
meanLength: meanLen,
|
|
2486
|
+
lengthCV: cv,
|
|
2487
|
+
targetLengthBand: [minBand, maxBand],
|
|
2488
|
+
concretenessPer100: conc,
|
|
2489
|
+
mattr: prof.lexical.mattr,
|
|
2490
|
+
emDashPer300: emDash,
|
|
2491
|
+
maxSemicolonsInSentence: prof.punctuation.maxSemicolonsInSentence,
|
|
2492
|
+
},
|
|
2493
|
+
profile: {
|
|
2494
|
+
tone,
|
|
2495
|
+
sentenceHabits,
|
|
2496
|
+
preferredPatterns,
|
|
2497
|
+
avoidPatterns,
|
|
2498
|
+
},
|
|
2499
|
+
};
|
|
2500
|
+
}
|