dislop 0.7.1 → 0.8.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/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +4 -3
- package/.cursor-plugin/plugin.json +3 -2
- package/PRODUCT.md +18 -4
- package/README.md +72 -38
- package/README.zh-CN.md +70 -40
- package/bin/dislop.mjs +2883 -309
- package/gemini-extension.json +2 -2
- package/package.json +19 -3
- package/packs/business-brief/pack.json +336 -6
- package/packs/core/pack.json +14 -7
- package/packs/deck-and-ui/pack.json +255 -6
- package/packs/literary-essay/pack.json +20 -0
- package/patterns/ai-tic-rubric.json +252 -0
- package/patterns/banks/composite-fusion.json +13 -1
- package/patterns/banks/lexical-signals.json +20 -2
- package/patterns/banks/syntactic-frames.json +10 -3
- package/patterns/banks/visual-deck.json +7 -0
- package/patterns/dimensions/discourse.json +26 -0
- package/patterns/dimensions/lexical.json +26 -0
- package/patterns/dimensions/rhythm.json +52 -0
- package/patterns/dimensions/visual-and-deck.json +209 -1
- package/plugin.json +4 -3
- package/server.json +2 -2
- package/skills/dislop/SKILL.md +35 -41
- package/skills/dislop/agents/openai.yaml +1 -1
- package/skills/dislop/references/essay.md +24 -0
- package/skills/dislop/references/essay.zh-CN.md +24 -0
- package/skills/dislop/references/office.md +23 -0
- package/skills/dislop/references/office.zh-CN.md +23 -0
- package/skills/dislop/references/web-ui.md +24 -0
- package/skills/dislop/references/web-ui.zh-CN.md +24 -0
- package/skills/dislop/references/work-docs.md +25 -0
- package/skills/dislop/references/work-docs.zh-CN.md +24 -0
- package/src/binary-node.mjs +1716 -1
- package/src/core.mjs +3215 -247
- package/src/local-model.mjs +31 -11
- package/src/pattern-engine.mjs +174 -24
- package/src/pocket-model.mjs +27 -5
- package/src/review-client.mjs +1064 -0
- package/skills/dislop/references/business-and-rfc.md +0 -26
- package/skills/dislop/references/editorial-and-essay.md +0 -20
- package/skills/dislop/references/regulated-and-precision.md +0 -27
- package/skills/dislop/references/web-ui-and-deck.md +0 -26
package/bin/dislop.mjs
CHANGED
|
@@ -1,19 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import readline from "node:readline";
|
|
5
|
-
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
6
7
|
import { fileURLToPath } from "node:url";
|
|
7
8
|
import {
|
|
8
9
|
ENGINE_VERSION,
|
|
9
10
|
SEVERITY_RANK,
|
|
11
|
+
VALID_REGISTERS,
|
|
10
12
|
fnv1aHex,
|
|
13
|
+
codePointLength,
|
|
11
14
|
detectModality,
|
|
12
15
|
defaultPackForModality,
|
|
16
|
+
isLongFormHtmlDocument,
|
|
17
|
+
hasEmbeddedUiMarkup,
|
|
18
|
+
deriveFixStrategy,
|
|
19
|
+
computeRulesetHash,
|
|
20
|
+
validateConfig,
|
|
21
|
+
resolveRegister,
|
|
22
|
+
applyRegisterOverride,
|
|
23
|
+
getScenarioStrategy,
|
|
24
|
+
computeFindingConfidence,
|
|
25
|
+
buildFindingRevision,
|
|
13
26
|
resolveEffectivePack,
|
|
27
|
+
buildZones,
|
|
14
28
|
auditText,
|
|
15
29
|
auditOoxmlEntries,
|
|
30
|
+
auditImageDocument,
|
|
31
|
+
auditPdfDocument,
|
|
16
32
|
analyzeTextProfile,
|
|
33
|
+
verifyRevision,
|
|
34
|
+
verifyRevisionBundle,
|
|
17
35
|
formatReport,
|
|
18
36
|
buildCatalog,
|
|
19
37
|
queryCatalog,
|
|
@@ -32,7 +50,19 @@ import {
|
|
|
32
50
|
removeInstalledModel,
|
|
33
51
|
runLocalDeslop,
|
|
34
52
|
} from "../src/local-model.mjs";
|
|
35
|
-
import { readZipXmlEntries } from "../src/binary-node.mjs";
|
|
53
|
+
import { parseImageBuffer, parsePdfBuffer, readZipXmlEntries } from "../src/binary-node.mjs";
|
|
54
|
+
import {
|
|
55
|
+
resolveProviderConfig,
|
|
56
|
+
inspectByokEnvStatus,
|
|
57
|
+
extractOoxmlReviewText,
|
|
58
|
+
chunkTextByParagraphs,
|
|
59
|
+
buildReviewPrompt,
|
|
60
|
+
runReviewRequest,
|
|
61
|
+
validateAndNormalizeReviewResponse,
|
|
62
|
+
assertLoopbackEndpoint,
|
|
63
|
+
scrubSecrets,
|
|
64
|
+
pingEndpointHealth,
|
|
65
|
+
} from "../src/review-client.mjs";
|
|
36
66
|
|
|
37
67
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
38
68
|
const REPO_ROOT = path.resolve(__dirname, "..");
|
|
@@ -80,36 +110,144 @@ function loadPatternLibrary(customPatternsDir = PATTERNS_DIR) {
|
|
|
80
110
|
return byRuleId;
|
|
81
111
|
}
|
|
82
112
|
|
|
113
|
+
function getUserConfigDir() {
|
|
114
|
+
if (process.env.DISLOP_CONFIG_HOME) {
|
|
115
|
+
return path.resolve(process.env.DISLOP_CONFIG_HOME);
|
|
116
|
+
}
|
|
117
|
+
const base = process.env.XDG_CONFIG_HOME ? path.resolve(process.env.XDG_CONFIG_HOME) : path.join(os.homedir(), ".config");
|
|
118
|
+
return path.join(base, "dislop");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function shouldSkipUserConfig(cwd, explicitConfigPath = null) {
|
|
122
|
+
if (explicitConfigPath || process.env.DISLOP_NO_USER_CONFIG === "1") return true;
|
|
123
|
+
const isSelfRepo =
|
|
124
|
+
fs.existsSync(path.join(cwd, "packs", "core", "pack.json")) &&
|
|
125
|
+
fs.existsSync(path.join(cwd, "src", "core.mjs"));
|
|
126
|
+
return isSelfRepo && !process.env.DISLOP_CONFIG_HOME;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function mergeConfigLayers(base, layer) {
|
|
130
|
+
if (!layer || typeof layer !== "object") return base;
|
|
131
|
+
return {
|
|
132
|
+
...base,
|
|
133
|
+
...layer,
|
|
134
|
+
rules: { ...(base.rules || {}), ...(layer.rules || {}) },
|
|
135
|
+
allow: [...(base.allow || []), ...(layer.allow || [])],
|
|
136
|
+
ignore: [...(base.ignore || []), ...(layer.ignore || [])],
|
|
137
|
+
forbid: [...(base.forbid || []), ...(layer.forbid || [])],
|
|
138
|
+
overrides: [...(base.overrides || []), ...(layer.overrides || [])],
|
|
139
|
+
proseFences: [...(base.proseFences || []), ...(layer.proseFences || [])],
|
|
140
|
+
...(layer.maskBlockquotes !== undefined ? { maskBlockquotes: layer.maskBlockquotes } : {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
class ConfigError extends Error {}
|
|
145
|
+
|
|
146
|
+
function readConfigJson(filePath) {
|
|
147
|
+
let raw;
|
|
148
|
+
try {
|
|
149
|
+
raw = fs.readFileSync(filePath, "utf8");
|
|
150
|
+
} catch (err) {
|
|
151
|
+
throw new ConfigError(`cannot read config '${filePath}': ${err.message}`);
|
|
152
|
+
}
|
|
153
|
+
let parsed;
|
|
154
|
+
try {
|
|
155
|
+
parsed = JSON.parse(raw);
|
|
156
|
+
} catch (err) {
|
|
157
|
+
throw new ConfigError(`invalid config '${filePath}': ${err.message}`);
|
|
158
|
+
}
|
|
159
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
160
|
+
throw new ConfigError(`invalid config '${filePath}': expected a JSON object`);
|
|
161
|
+
}
|
|
162
|
+
return parsed;
|
|
163
|
+
}
|
|
164
|
+
|
|
83
165
|
function loadConfig(cwd = process.cwd(), explicitConfigPath = null) {
|
|
84
166
|
let base = {};
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
167
|
+
if (!shouldSkipUserConfig(cwd, explicitConfigPath)) {
|
|
168
|
+
const userCfgPath = path.join(getUserConfigDir(), "config.json");
|
|
169
|
+
if (fs.existsSync(userCfgPath)) {
|
|
170
|
+
base = mergeConfigLayers(base, readConfigJson(userCfgPath));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (explicitConfigPath) {
|
|
174
|
+
const resolved = path.resolve(cwd, explicitConfigPath);
|
|
175
|
+
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
|
|
176
|
+
throw new ConfigError(`config file not found: ${explicitConfigPath}`);
|
|
177
|
+
}
|
|
178
|
+
base = mergeConfigLayers(base, readConfigJson(resolved));
|
|
179
|
+
} else {
|
|
180
|
+
const candidates = [
|
|
181
|
+
path.join(cwd, ".dislop.json"),
|
|
182
|
+
path.join(cwd, "dislop.json"),
|
|
183
|
+
path.join(cwd, ".disloprc.json"),
|
|
184
|
+
];
|
|
185
|
+
for (const candidate of candidates) {
|
|
186
|
+
if (fs.existsSync(candidate)) {
|
|
187
|
+
base = mergeConfigLayers(base, readConfigJson(candidate));
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
97
190
|
}
|
|
98
191
|
}
|
|
99
192
|
|
|
100
193
|
const localPath = path.join(cwd, ".dislop.local.json");
|
|
101
194
|
if (fs.existsSync(localPath)) {
|
|
102
|
-
|
|
103
|
-
base = {
|
|
104
|
-
...base,
|
|
105
|
-
...localCfg,
|
|
106
|
-
rules: { ...(base.rules || {}), ...(localCfg.rules || {}) },
|
|
107
|
-
allow: [...(base.allow || []), ...(localCfg.allow || [])],
|
|
108
|
-
ignore: [...(base.ignore || []), ...(localCfg.ignore || [])],
|
|
109
|
-
forbid: [...(base.forbid || []), ...(localCfg.forbid || [])],
|
|
110
|
-
};
|
|
195
|
+
base = mergeConfigLayers(base, readConfigJson(localPath));
|
|
111
196
|
}
|
|
112
|
-
|
|
197
|
+
try {
|
|
198
|
+
return validateConfig(base);
|
|
199
|
+
} catch (err) {
|
|
200
|
+
throw new ConfigError(err.message);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function loadConfigOrExit(cwd = process.cwd(), explicitConfigPath = null) {
|
|
205
|
+
try {
|
|
206
|
+
return loadConfig(cwd, explicitConfigPath);
|
|
207
|
+
} catch (err) {
|
|
208
|
+
console.error(`dislop: ${err.message}`);
|
|
209
|
+
process.exit(2);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function summarizeReportContext(regPairs = [], flagRegister = null) {
|
|
214
|
+
if (flagRegister && String(flagRegister).trim().toLowerCase() !== "auto") {
|
|
215
|
+
return { register: String(flagRegister).trim().toLowerCase(), registerSource: "flag" };
|
|
216
|
+
}
|
|
217
|
+
if (!regPairs || regPairs.length === 0) {
|
|
218
|
+
return { register: "unspecified", registerSource: "default" };
|
|
219
|
+
}
|
|
220
|
+
const regs = new Set(regPairs.map((r) => r.register));
|
|
221
|
+
const srcs = new Set(regPairs.map((r) => r.registerSource));
|
|
222
|
+
if (regs.size === 1) {
|
|
223
|
+
const register = regPairs[0].register;
|
|
224
|
+
const registerSource = srcs.size === 1 ? regPairs[0].registerSource : "mixed";
|
|
225
|
+
return { register, registerSource };
|
|
226
|
+
}
|
|
227
|
+
return { register: "mixed", registerSource: "mixed" };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function discoverVoiceCard(cwd = process.cwd()) {
|
|
231
|
+
const candidates = [
|
|
232
|
+
["local", path.join(cwd, ".dislop.local", "voice.json")],
|
|
233
|
+
["project", path.join(cwd, ".dislop", "voice.json")],
|
|
234
|
+
];
|
|
235
|
+
if (!shouldSkipUserConfig(cwd, null)) {
|
|
236
|
+
candidates.push(["user", path.join(getUserConfigDir(), "voice.json")]);
|
|
237
|
+
}
|
|
238
|
+
for (const [scope, p] of candidates) {
|
|
239
|
+
if (fs.existsSync(p)) {
|
|
240
|
+
try {
|
|
241
|
+
const card = JSON.parse(fs.readFileSync(p, "utf8"));
|
|
242
|
+
if (card && typeof card === "object" && !Array.isArray(card)) {
|
|
243
|
+
return { found: true, scope, card };
|
|
244
|
+
}
|
|
245
|
+
} catch {
|
|
246
|
+
// ignore unreadable voice card
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return { found: false, scope: null, card: null };
|
|
113
251
|
}
|
|
114
252
|
|
|
115
253
|
function expandBraces(pattern) {
|
|
@@ -152,15 +290,47 @@ function matchesAnyGlob(relPosix, globs = []) {
|
|
|
152
290
|
return globs.flatMap(expandBraces).some((g) => globToRegExp(g).test(clean));
|
|
153
291
|
}
|
|
154
292
|
|
|
155
|
-
function
|
|
156
|
-
|
|
293
|
+
function resolveConfigForFile(relPosix, config = {}) {
|
|
294
|
+
let merged = {
|
|
295
|
+
...config,
|
|
296
|
+
rules: { ...(config.rules || {}) },
|
|
297
|
+
allow: [...(config.allow || [])],
|
|
298
|
+
forbid: [...(config.forbid || [])],
|
|
299
|
+
proseFences: [...(config.proseFences || [])],
|
|
300
|
+
};
|
|
157
301
|
for (const ov of config?.overrides || []) {
|
|
158
302
|
const patterns = Array.isArray(ov.files) ? ov.files : [ov.files];
|
|
159
|
-
if (
|
|
160
|
-
|
|
161
|
-
|
|
303
|
+
if (!matchesAnyGlob(relPosix, patterns)) continue;
|
|
304
|
+
merged = {
|
|
305
|
+
...merged,
|
|
306
|
+
...(ov.pack ? { pack: ov.pack } : {}),
|
|
307
|
+
rules: { ...merged.rules, ...(ov.rules || {}) },
|
|
308
|
+
allow: [...merged.allow, ...(ov.allow || [])],
|
|
309
|
+
forbid: [...merged.forbid, ...(ov.forbid || [])],
|
|
310
|
+
proseFences: [...merged.proseFences, ...(ov.proseFences || [])],
|
|
311
|
+
...(ov.maskBlockquotes !== undefined ? { maskBlockquotes: ov.maskBlockquotes } : {}),
|
|
312
|
+
};
|
|
162
313
|
}
|
|
163
|
-
|
|
314
|
+
return merged;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function mergePacks(primaryPack, extraPack) {
|
|
318
|
+
const byId = new Map();
|
|
319
|
+
for (const r of extraPack.rules || []) byId.set(r.id, r);
|
|
320
|
+
for (const r of primaryPack.rules || []) byId.set(r.id, r);
|
|
321
|
+
return {
|
|
322
|
+
...extraPack,
|
|
323
|
+
...primaryPack,
|
|
324
|
+
id: `${primaryPack.id}+${extraPack.id}`,
|
|
325
|
+
thresholds: { ...(extraPack.thresholds || {}), ...(primaryPack.thresholds || {}) },
|
|
326
|
+
rules: Array.from(byId.values()),
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function pickPackForFile(relPosix, modality, explicitPack, config) {
|
|
331
|
+
if (explicitPack && explicitPack !== "auto") return explicitPack;
|
|
332
|
+
const resolvedCfg = resolveConfigForFile(relPosix, config);
|
|
333
|
+
if (resolvedCfg?.pack && explicitPack !== "auto") return resolvedCfg.pack;
|
|
164
334
|
return defaultPackForModality(modality);
|
|
165
335
|
}
|
|
166
336
|
|
|
@@ -169,7 +339,7 @@ function decodeUtf8Strict(buffer) {
|
|
|
169
339
|
return decoder.decode(buffer);
|
|
170
340
|
}
|
|
171
341
|
|
|
172
|
-
function collectFiles(targetPaths, cwd, config) {
|
|
342
|
+
function collectFiles(targetPaths, cwd, config, explicitTargets = true) {
|
|
173
343
|
const realCwd = fs.existsSync(cwd) ? fs.realpathSync(cwd) : cwd;
|
|
174
344
|
const files = [];
|
|
175
345
|
const skipped = [];
|
|
@@ -204,7 +374,7 @@ function collectFiles(targetPaths, cwd, config) {
|
|
|
204
374
|
if (stat.isDirectory()) {
|
|
205
375
|
const entries = fs
|
|
206
376
|
.readdirSync(canonicalPath, { withFileTypes: true })
|
|
207
|
-
.sort((a, b) => a.name.
|
|
377
|
+
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
208
378
|
for (const entry of entries) {
|
|
209
379
|
if (DEFAULT_IGNORE_DIRS.has(entry.name)) continue;
|
|
210
380
|
walk(path.join(canonicalPath, entry.name), false);
|
|
@@ -224,36 +394,117 @@ function collectFiles(targetPaths, cwd, config) {
|
|
|
224
394
|
}
|
|
225
395
|
|
|
226
396
|
for (const t of targetPaths) {
|
|
227
|
-
walk(path.resolve(realCwd, t),
|
|
397
|
+
walk(path.resolve(realCwd, t), explicitTargets);
|
|
228
398
|
}
|
|
229
399
|
return { files, skipped };
|
|
230
400
|
}
|
|
231
401
|
|
|
402
|
+
const PROSE_ML_MODALITIES = new Set(["markdown", "text", "html", "svg"]);
|
|
403
|
+
|
|
404
|
+
function buildCodepointLineStarts(text) {
|
|
405
|
+
const starts = [0];
|
|
406
|
+
let cpIdx = 0;
|
|
407
|
+
for (const ch of String(text || "")) {
|
|
408
|
+
cpIdx += 1;
|
|
409
|
+
if (ch === "\n") starts.push(cpIdx);
|
|
410
|
+
}
|
|
411
|
+
return starts;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function cpOffsetToLine(cpStarts, cpOff) {
|
|
415
|
+
let lo = 0;
|
|
416
|
+
let hi = cpStarts.length - 1;
|
|
417
|
+
while (lo <= hi) {
|
|
418
|
+
const mid = (lo + hi) >> 1;
|
|
419
|
+
if (cpStarts[mid] <= cpOff) lo = mid + 1;
|
|
420
|
+
else hi = mid - 1;
|
|
421
|
+
}
|
|
422
|
+
return Math.max(0, hi) + 1;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function unquoteGitPath(rawPath) {
|
|
426
|
+
const s = String(rawPath || "");
|
|
427
|
+
if (s.length < 2 || !s.startsWith('"') || !s.endsWith('"')) return s;
|
|
428
|
+
const inner = s.slice(1, -1);
|
|
429
|
+
const bytes = [];
|
|
430
|
+
const pushStr = (str) => {
|
|
431
|
+
for (const b of Buffer.from(str, "utf8")) bytes.push(b);
|
|
432
|
+
};
|
|
433
|
+
const escMap = { a: "\x07", b: "\x08", f: "\x0c", n: "\n", r: "\r", t: "\t", v: "\x0b", "\\": "\\", '"': '"' };
|
|
434
|
+
for (let i = 0; i < inner.length; i += 1) {
|
|
435
|
+
const ch = inner[i];
|
|
436
|
+
if (ch !== "\\") {
|
|
437
|
+
pushStr(ch);
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
if (i + 1 >= inner.length) {
|
|
441
|
+
bytes.push(0x5c);
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
const next = inner[i + 1];
|
|
445
|
+
if (/[0-7]{3}/.test(inner.slice(i + 1, i + 4))) {
|
|
446
|
+
bytes.push(parseInt(inner.slice(i + 1, i + 4), 8));
|
|
447
|
+
i += 3;
|
|
448
|
+
} else if (next in escMap) {
|
|
449
|
+
pushStr(escMap[next]);
|
|
450
|
+
i += 1;
|
|
451
|
+
} else {
|
|
452
|
+
pushStr(next);
|
|
453
|
+
i += 1;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return Buffer.from(bytes).toString("utf8");
|
|
457
|
+
}
|
|
458
|
+
|
|
232
459
|
function getChangedLineMap(cwd, gitRef, staged = false) {
|
|
233
460
|
const args = staged
|
|
234
|
-
? [
|
|
235
|
-
|
|
461
|
+
? [
|
|
462
|
+
"-c", "core.quotepath=off",
|
|
463
|
+
"-c", "diff.interHunkContext=0",
|
|
464
|
+
"diff", "--cached",
|
|
465
|
+
"--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "--relative",
|
|
466
|
+
"-U0", "--no-color", "--",
|
|
467
|
+
]
|
|
468
|
+
: [
|
|
469
|
+
"-c", "core.quotepath=off",
|
|
470
|
+
"-c", "diff.interHunkContext=0",
|
|
471
|
+
"diff",
|
|
472
|
+
"--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "--relative",
|
|
473
|
+
"-U0", "--no-color", gitRef || "HEAD", "--",
|
|
474
|
+
];
|
|
236
475
|
const diffOut = execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 32 * 1024 * 1024 });
|
|
237
476
|
const changed = new Map(); // relPath -> Set<line> | "ALL"
|
|
238
477
|
let currentFile = null;
|
|
478
|
+
let inHunk = false;
|
|
239
479
|
|
|
240
480
|
for (const line of diffOut.split(/\r?\n/)) {
|
|
241
481
|
if (line.startsWith("diff --git ")) {
|
|
242
|
-
|
|
243
|
-
currentFile =
|
|
244
|
-
} else if (line.startsWith("+++ b/")) {
|
|
245
|
-
|
|
246
|
-
if (
|
|
247
|
-
|
|
248
|
-
|
|
482
|
+
inHunk = false;
|
|
483
|
+
currentFile = null;
|
|
484
|
+
} else if (!inHunk && (line.startsWith("+++ b/") || line.startsWith('+++ "b/'))) {
|
|
485
|
+
const target = unquoteGitPath(line.slice(4));
|
|
486
|
+
if (target.startsWith("b/")) {
|
|
487
|
+
currentFile = target.slice(2);
|
|
488
|
+
if (!changed.has(currentFile)) changed.set(currentFile, new Set());
|
|
489
|
+
}
|
|
490
|
+
} else if (!inHunk && line.startsWith("Binary files ")) {
|
|
491
|
+
const bm = line.match(/^Binary files .* and (b\/.+|"b\/.+") differ$/);
|
|
492
|
+
if (bm) {
|
|
493
|
+
const binTarget = unquoteGitPath(bm[1]);
|
|
494
|
+
if (binTarget.startsWith("b/")) {
|
|
495
|
+
changed.set(binTarget.slice(2), "ALL");
|
|
496
|
+
}
|
|
497
|
+
}
|
|
249
498
|
} else if (line.startsWith("@@ ") && currentFile) {
|
|
499
|
+
inHunk = true;
|
|
250
500
|
const m = line.match(/\+(\d+)(?:,(\d+))?/);
|
|
251
501
|
if (m) {
|
|
252
502
|
const start = Number(m[1]);
|
|
253
503
|
const count = m[2] !== undefined ? Number(m[2]) : 1;
|
|
504
|
+
if (count === 0) continue;
|
|
254
505
|
const set = changed.get(currentFile);
|
|
255
506
|
if (set instanceof Set) {
|
|
256
|
-
for (let k = 0; k <
|
|
507
|
+
for (let k = 0; k < count; k += 1) {
|
|
257
508
|
set.add(start + k);
|
|
258
509
|
}
|
|
259
510
|
}
|
|
@@ -263,9 +514,27 @@ function getChangedLineMap(cwd, gitRef, staged = false) {
|
|
|
263
514
|
return changed;
|
|
264
515
|
}
|
|
265
516
|
|
|
266
|
-
function
|
|
517
|
+
function filterDriversWithProfile(drivers, profile) {
|
|
518
|
+
if (!Array.isArray(drivers) || !profile) return drivers || [];
|
|
519
|
+
return drivers.filter((d) => {
|
|
520
|
+
const feat = String(d.feature || "");
|
|
521
|
+
if (profile.concreteness?.status === "grounded" && feat.includes("concreteness")) {
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
if (profile.burstiness?.status === "varied" && feat.includes("sent_cv")) {
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
return true;
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function buildPocketMlFindings(text, filename, existingFindings, threshold = null, { profile = null, modality = null, register = "unspecified" } = {}) {
|
|
532
|
+
if (register === "technical") {
|
|
533
|
+
return { doc: { documentProbability: 0, paragraphs: [], flaggedCount: 0 }, findings: [] };
|
|
534
|
+
}
|
|
267
535
|
const doc = analyzeDocumentWithPocketModels(text, { threshold });
|
|
268
536
|
const extras = [];
|
|
537
|
+
const textLines = String(text || "").split(/\r?\n/);
|
|
269
538
|
for (const p of doc.paragraphs) {
|
|
270
539
|
if (!p.flagged) continue;
|
|
271
540
|
const overlapsExisting = existingFindings.some(
|
|
@@ -273,20 +542,33 @@ function buildPocketMlFindings(text, filename, existingFindings, threshold = nul
|
|
|
273
542
|
);
|
|
274
543
|
if (overlapsExisting) continue;
|
|
275
544
|
const pct = Math.round(p.slopProbability * 100);
|
|
276
|
-
const
|
|
277
|
-
const
|
|
545
|
+
const activeDrivers = filterDriversWithProfile(p.topDrivers, profile);
|
|
546
|
+
const drvEn = activeDrivers.map((d) => d.reason.en).join("; ") || "uniform abstract phrasing";
|
|
547
|
+
const drvZh = activeDrivers.map((d) => d.reason.zh).join("、") || "句式与用词高度均质";
|
|
278
548
|
const loc = String(p.startLine);
|
|
279
549
|
const cleanExcerpt = String(p.excerpt || "");
|
|
550
|
+
const fullPara = textLines.slice(Math.max(0, p.startLine - 1), p.endLine).join("\n") || cleanExcerpt;
|
|
280
551
|
const fp = `pocket-stealth-vapor:${fnv1aHex(`pocket-stealth-vapor|${cleanExcerpt.toLowerCase()}|${loc}`)}`;
|
|
552
|
+
const msgObj = {
|
|
553
|
+
en: `Paragraph reads as predictable low-concreteness AI filler (${pct}% pocket-ML score: ${drvEn}).`,
|
|
554
|
+
zh: `段落呈高度可预测、低事实密度的温吞水套话(内置模型评分 ${pct}%:${drvZh})。`,
|
|
555
|
+
};
|
|
556
|
+
const delObj = {
|
|
557
|
+
en: "Cut this paragraph or replace abstract cushion wrappers with one concrete event, number, file path, or direct action.",
|
|
558
|
+
zh: "删掉整段空泛铺垫,或把抽象缓冲外壳直接换成具体事件、数字、文件路径或明确动作。",
|
|
559
|
+
};
|
|
560
|
+
const effMod = modality || detectModality(filename) || "markdown";
|
|
281
561
|
extras.push({
|
|
282
562
|
fingerprint: fp,
|
|
283
563
|
ruleId: "pocket-stealth-vapor",
|
|
284
564
|
packId: "pocket-model",
|
|
285
565
|
severity: "warning",
|
|
566
|
+
confidence: computeFindingConfidence({ ruleId: "pocket-stealth-vapor", tier: "taste", severity: "warning" }),
|
|
286
567
|
tier: "taste",
|
|
568
|
+
fixStrategy: "rephrase",
|
|
287
569
|
family: "rhythm/pocket-stealth-vapor",
|
|
288
570
|
category: "statistical-vapor",
|
|
289
|
-
modality:
|
|
571
|
+
modality: effMod,
|
|
290
572
|
file: filename,
|
|
291
573
|
location: loc,
|
|
292
574
|
line: p.startLine,
|
|
@@ -295,14 +577,18 @@ function buildPocketMlFindings(text, filename, existingFindings, threshold = nul
|
|
|
295
577
|
match: cleanExcerpt,
|
|
296
578
|
excerpt: cleanExcerpt,
|
|
297
579
|
mlProbability: p.slopProbability,
|
|
298
|
-
message:
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
580
|
+
message: msgObj,
|
|
581
|
+
deletionTest: delObj,
|
|
582
|
+
revision: buildFindingRevision({
|
|
583
|
+
ruleId: "pocket-stealth-vapor",
|
|
584
|
+
tier: "taste",
|
|
585
|
+
family: "rhythm/pocket-stealth-vapor",
|
|
586
|
+
modality: effMod,
|
|
587
|
+
message: msgObj,
|
|
588
|
+
deletionTest: delObj,
|
|
589
|
+
sentence: fullPara,
|
|
590
|
+
fixStrategy: "rephrase",
|
|
591
|
+
}),
|
|
306
592
|
});
|
|
307
593
|
}
|
|
308
594
|
return { doc, findings: extras };
|
|
@@ -318,55 +604,313 @@ function summarizePocketForProfile(text) {
|
|
|
318
604
|
};
|
|
319
605
|
}
|
|
320
606
|
|
|
321
|
-
function
|
|
607
|
+
function lookupRuleAcrossPacks(packs, pack, ruleId) {
|
|
608
|
+
const inPack = (pack?.rules || []).find((r) => r.id === ruleId);
|
|
609
|
+
if (inPack) return inPack;
|
|
610
|
+
for (const p of Object.values(packs || {})) {
|
|
611
|
+
const found = (p?.rules || []).find((r) => r.id === ruleId);
|
|
612
|
+
if (found) return found;
|
|
613
|
+
}
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function mergePatternBankFindings(existingFindings, patFindings, { packs = null, pack = null, register = "unspecified", config = {} } = {}) {
|
|
322
618
|
const seen = new Set(existingFindings.map((f) => `${f.ruleId}:${f.line}`));
|
|
323
619
|
const out = [...existingFindings];
|
|
324
620
|
for (const pf of patFindings || []) {
|
|
325
621
|
const key = `${pf.ruleId}:${pf.line}`;
|
|
326
622
|
if (seen.has(key)) continue;
|
|
623
|
+
const ruleRef = lookupRuleAcrossPacks(packs, pack, pf.ruleId);
|
|
624
|
+
let registerAdjusted = false;
|
|
625
|
+
let effSev = pf.severity || "info";
|
|
626
|
+
let effMsg = pf.message;
|
|
627
|
+
let effDel = pf.deletionTest || ruleRef?.deletionTest || null;
|
|
628
|
+
if (ruleRef) {
|
|
629
|
+
const regApplied = applyRegisterOverride(ruleRef, register, config);
|
|
630
|
+
if (regApplied.skip) continue;
|
|
631
|
+
if (regApplied.registerAdjusted) {
|
|
632
|
+
registerAdjusted = true;
|
|
633
|
+
effSev = regApplied.rule.severity || effSev;
|
|
634
|
+
if (regApplied.rule.message) effMsg = regApplied.rule.message;
|
|
635
|
+
if (regApplied.rule.deletionTest) effDel = regApplied.rule.deletionTest;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
327
638
|
seen.add(key);
|
|
328
|
-
|
|
639
|
+
const fam = pf.family || (pf.dimension ? `${pf.dimension}/${pf.ruleId}` : "pattern-bank");
|
|
640
|
+
const mod = pf.modality || "markdown";
|
|
641
|
+
const revScope =
|
|
642
|
+
ruleRef?.revisionScope ||
|
|
643
|
+
(pf.ruleId === "low-burstiness-vapor" ? "paragraph" : null);
|
|
644
|
+
const fixStrat = pf.fixStrategy || deriveFixStrategy({ id: pf.ruleId, family: fam });
|
|
645
|
+
out.push({
|
|
646
|
+
...pf,
|
|
647
|
+
severity: effSev,
|
|
648
|
+
fixStrategy: fixStrat,
|
|
649
|
+
message: effMsg,
|
|
650
|
+
...(effDel ? { deletionTest: effDel } : {}),
|
|
651
|
+
confidence: pf.confidence || computeFindingConfidence({ ruleId: pf.ruleId, tier: pf.tier || "taste", severity: effSev, registerAdjusted }),
|
|
652
|
+
revision:
|
|
653
|
+
pf.revision ||
|
|
654
|
+
buildFindingRevision({
|
|
655
|
+
ruleId: pf.ruleId,
|
|
656
|
+
tier: pf.tier || "taste",
|
|
657
|
+
family: fam,
|
|
658
|
+
modality: mod,
|
|
659
|
+
message: effMsg,
|
|
660
|
+
deletionTest: effDel,
|
|
661
|
+
sentence: String(pf.match || ""),
|
|
662
|
+
revisionKind: ruleRef?.revisionKind || null,
|
|
663
|
+
revisionScope: revScope,
|
|
664
|
+
revisionAvoid: ruleRef?.revisionAvoid || null,
|
|
665
|
+
fixStrategy: fixStrat,
|
|
666
|
+
}),
|
|
667
|
+
});
|
|
329
668
|
}
|
|
330
669
|
return out;
|
|
331
670
|
}
|
|
332
671
|
|
|
333
|
-
function
|
|
672
|
+
function collectTextCoverageWarnings(text, modality, rel, profile) {
|
|
673
|
+
const warnings = [];
|
|
674
|
+
if (
|
|
675
|
+
modality === "html" &&
|
|
676
|
+
/<script\b[^>]*\btype\s*=\s*(?:"application\/json"|'application\/json'|application\/json(?=[\s>]))/i.test(text)
|
|
677
|
+
) {
|
|
678
|
+
const zones = buildZones(text, "html");
|
|
679
|
+
if (codePointLength(zones.prose.replace(/\s+/g, "")) < 120) {
|
|
680
|
+
warnings.push({
|
|
681
|
+
file: rel,
|
|
682
|
+
code: "spa-json-shell",
|
|
683
|
+
message: "HTML appears to be an SPA shell with <script type=\"application/json\"> data and <120 visible prose chars; inspect JSON payload or rendered DOM.",
|
|
684
|
+
});
|
|
685
|
+
return warnings;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const textCpLen = codePointLength(text);
|
|
689
|
+
if ((modality === "markdown" || modality === "text" || modality === "html") && textCpLen >= 2000 && profile && profile.proseCoverage < 0.15) {
|
|
690
|
+
if (modality === "html") {
|
|
691
|
+
warnings.push({
|
|
692
|
+
file: rel,
|
|
693
|
+
code: "low-prose-coverage",
|
|
694
|
+
message: `Extracted prose covers only ${Math.round(profile.proseCoverage * 100)}% of file (${textCpLen} chars); check fenced blocks/markup if unexpected.`,
|
|
695
|
+
});
|
|
696
|
+
return warnings;
|
|
697
|
+
}
|
|
698
|
+
const nonEmptyLines = text.split(/\r?\n/).filter((l) => l.trim().length > 0);
|
|
699
|
+
const tableOrLinkLines = nonEmptyLines.filter((l) => /^\s*(?:\||[-*+]\s+\[)/.test(l)).length;
|
|
700
|
+
if (nonEmptyLines.length > 0 && tableOrLinkLines / nonEmptyLines.length < 0.5) {
|
|
701
|
+
warnings.push({
|
|
702
|
+
file: rel,
|
|
703
|
+
code: "low-prose-coverage",
|
|
704
|
+
message: `Extracted prose covers only ${Math.round(profile.proseCoverage * 100)}% of file (${textCpLen} chars); check fenced blocks/markup if unexpected.`,
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return warnings;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function selectPackWithConfidenceFloor(routeRes) {
|
|
712
|
+
const rec = routeRes?.recommendedPack || "business-brief";
|
|
713
|
+
const conf = Number(routeRes?.confidence || 0);
|
|
714
|
+
if (rec === "business-brief") return { packId: "business-brief", packSource: "auto-pocket-router" };
|
|
715
|
+
if (rec === "deck-and-ui" && conf >= 0.6) return { packId: "deck-and-ui", packSource: "auto-pocket-router" };
|
|
716
|
+
if (rec !== "deck-and-ui" && conf >= 0.65) return { packId: rec, packSource: "auto-pocket-router" };
|
|
717
|
+
return { packId: "business-brief", packSource: "auto-default-fallback" };
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function resolveTextPackAndSource(text, rel, modality, explicitPack, fileConfig, packs) {
|
|
721
|
+
let pack;
|
|
722
|
+
let effectivePack;
|
|
723
|
+
let packSource;
|
|
724
|
+
if (explicitPack && explicitPack !== "auto") {
|
|
725
|
+
pack = resolveEffectivePack(explicitPack, packs, fileConfig);
|
|
726
|
+
effectivePack = explicitPack;
|
|
727
|
+
packSource = "cli-flag";
|
|
728
|
+
} else if (explicitPack === "auto" && (modality === "markdown" || modality === "text")) {
|
|
729
|
+
const sel = selectPackWithConfidenceFloor(predictPackWithPocketRouter(text));
|
|
730
|
+
const routed = sel.packId;
|
|
731
|
+
if (modality === "markdown" && hasEmbeddedUiMarkup(text)) {
|
|
732
|
+
let prosePackId = routed;
|
|
733
|
+
if (prosePackId === "deck-and-ui") {
|
|
734
|
+
const stripped = text.replace(/<[^>]+>/g, " ");
|
|
735
|
+
const strippedCjk = (stripped.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
736
|
+
const strippedWords = stripped.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
|
|
737
|
+
if (strippedCjk >= 20 || strippedWords >= 12) {
|
|
738
|
+
const rerouted = selectPackWithConfidenceFloor(predictPackWithPocketRouter(stripped)).packId;
|
|
739
|
+
prosePackId = rerouted === "deck-and-ui" ? "business-brief" : rerouted;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (prosePackId !== "deck-and-ui") {
|
|
743
|
+
const prosePack = resolveEffectivePack(prosePackId, packs, fileConfig);
|
|
744
|
+
const uiPack = resolveEffectivePack("deck-and-ui", packs, fileConfig);
|
|
745
|
+
pack = mergePacks(prosePack, uiPack);
|
|
746
|
+
effectivePack = `${prosePackId}+deck-and-ui`;
|
|
747
|
+
packSource = "auto-mixed-ui";
|
|
748
|
+
} else {
|
|
749
|
+
pack = resolveEffectivePack(routed, packs, fileConfig);
|
|
750
|
+
effectivePack = routed;
|
|
751
|
+
packSource = sel.packSource;
|
|
752
|
+
}
|
|
753
|
+
} else {
|
|
754
|
+
pack = resolveEffectivePack(routed, packs, fileConfig);
|
|
755
|
+
effectivePack = routed;
|
|
756
|
+
packSource = sel.packSource;
|
|
757
|
+
}
|
|
758
|
+
} else if (explicitPack === "auto" && modality === "html" && isLongFormHtmlDocument(text)) {
|
|
759
|
+
const biz = resolveEffectivePack("business-brief", packs, fileConfig);
|
|
760
|
+
const ui = resolveEffectivePack("deck-and-ui", packs, fileConfig);
|
|
761
|
+
pack = mergePacks(biz, ui);
|
|
762
|
+
effectivePack = "business-brief+deck-and-ui";
|
|
763
|
+
packSource = "auto-html-longform";
|
|
764
|
+
} else {
|
|
765
|
+
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
766
|
+
pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
767
|
+
effectivePack = packId;
|
|
768
|
+
packSource = explicitPack === "auto" ? "auto-modality" : fileConfig.pack ? "config" : "default-modality";
|
|
769
|
+
}
|
|
770
|
+
return { pack, effectivePack, packSource };
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function inspectSingleFile({ absPath, rel, modality }, packs, explicitPack, config, { includeMl = false, includePatterns = false, includeProfile = false, banks = null, register = null } = {}) {
|
|
334
774
|
const stat = fs.statSync(absPath);
|
|
335
775
|
if (stat.size > 25 * 1024 * 1024) {
|
|
336
776
|
return {
|
|
337
777
|
checked: false,
|
|
338
778
|
findings: [],
|
|
339
779
|
unusedSuppressions: [],
|
|
780
|
+
coverageWarnings: [],
|
|
340
781
|
skipped: [{ file: rel, reason: "File exceeds 25 MB single-file inspection cap" }],
|
|
341
782
|
};
|
|
342
783
|
}
|
|
343
784
|
|
|
785
|
+
const fileConfig = resolveConfigForFile(rel, config);
|
|
344
786
|
const buf = fs.readFileSync(absPath);
|
|
345
787
|
|
|
346
788
|
if (modality === "docx" || modality === "pptx") {
|
|
347
|
-
const
|
|
348
|
-
const
|
|
349
|
-
const
|
|
789
|
+
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
790
|
+
const pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
791
|
+
const packSource = explicitPack && explicitPack !== "auto" ? "cli-flag" : explicitPack === "auto" ? "auto-modality" : fileConfig.pack ? "config" : "default-modality";
|
|
792
|
+
const regInfo = resolveRegister("", { filename: rel, flagRegister: register, config: fileConfig });
|
|
350
793
|
try {
|
|
351
794
|
const entries = readZipXmlEntries(buf);
|
|
352
|
-
const res = auditOoxmlEntries(entries, { filename: rel, modality, pack, config });
|
|
795
|
+
const res = auditOoxmlEntries(entries, { filename: rel, modality, pack, config: fileConfig, register });
|
|
353
796
|
const missingCorePart = res.skipped.some((s) => s.file === rel);
|
|
354
797
|
let findings = res.findings;
|
|
355
798
|
if (includePatterns && !missingCorePart) {
|
|
356
|
-
const patRes = auditPatterns("", { filename: rel, modality, banks: banks || loadPatternBanks(), ooxml: entries });
|
|
357
|
-
findings = mergePatternBankFindings(findings, patRes.findings);
|
|
799
|
+
const patRes = auditPatterns("", { filename: rel, modality, banks: banks || loadPatternBanks(), ooxml: entries, config: fileConfig });
|
|
800
|
+
findings = mergePatternBankFindings(findings, patRes.findings, { packs, pack, register: regInfo.register, config: fileConfig });
|
|
358
801
|
}
|
|
359
|
-
return {
|
|
802
|
+
return {
|
|
803
|
+
checked: !missingCorePart,
|
|
804
|
+
findings,
|
|
805
|
+
unusedSuppressions: [],
|
|
806
|
+
coverageWarnings: [],
|
|
807
|
+
skipped: res.skipped,
|
|
808
|
+
effectivePack: packId,
|
|
809
|
+
packSource,
|
|
810
|
+
rulesetHash: computeRulesetHash(pack),
|
|
811
|
+
register: regInfo.register,
|
|
812
|
+
registerSource: regInfo.registerSource,
|
|
813
|
+
};
|
|
360
814
|
} catch (err) {
|
|
361
815
|
return {
|
|
362
816
|
checked: false,
|
|
363
817
|
findings: [],
|
|
364
818
|
unusedSuppressions: [],
|
|
819
|
+
coverageWarnings: [],
|
|
365
820
|
skipped: [{ file: rel, reason: `Uninspectable ${modality.toUpperCase()} archive: ${err.message}` }],
|
|
366
821
|
};
|
|
367
822
|
}
|
|
368
823
|
}
|
|
369
824
|
|
|
825
|
+
if (modality === "image") {
|
|
826
|
+
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
827
|
+
const pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
828
|
+
const packSource = explicitPack && explicitPack !== "auto" ? "cli-flag" : explicitPack === "auto" ? "auto-modality" : fileConfig.pack ? "config" : "default-modality";
|
|
829
|
+
const regInfo = resolveRegister("", { filename: rel, flagRegister: register, config: fileConfig });
|
|
830
|
+
try {
|
|
831
|
+
const parsed = parseImageBuffer(buf);
|
|
832
|
+
const res = auditImageDocument(parsed, { filename: rel, pack, config: fileConfig });
|
|
833
|
+
return {
|
|
834
|
+
checked: true,
|
|
835
|
+
findings: res.findings,
|
|
836
|
+
unusedSuppressions: [],
|
|
837
|
+
coverageWarnings: [],
|
|
838
|
+
skipped: res.skipped,
|
|
839
|
+
effectivePack: packId,
|
|
840
|
+
packSource,
|
|
841
|
+
rulesetHash: computeRulesetHash(pack),
|
|
842
|
+
register: regInfo.register,
|
|
843
|
+
registerSource: regInfo.registerSource,
|
|
844
|
+
};
|
|
845
|
+
} catch (err) {
|
|
846
|
+
return {
|
|
847
|
+
checked: false,
|
|
848
|
+
findings: [],
|
|
849
|
+
unusedSuppressions: [],
|
|
850
|
+
coverageWarnings: [],
|
|
851
|
+
skipped: [{ file: rel, reason: `Uninspectable image: ${err.message}` }],
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
if (modality === "pdf") {
|
|
857
|
+
const regInfo = resolveRegister("", { filename: rel, flagRegister: register, config: fileConfig });
|
|
858
|
+
try {
|
|
859
|
+
const parsed = parsePdfBuffer(buf);
|
|
860
|
+
let pack;
|
|
861
|
+
let effectivePack;
|
|
862
|
+
let packSource;
|
|
863
|
+
if (explicitPack && explicitPack !== "auto") {
|
|
864
|
+
pack = resolveEffectivePack(explicitPack, packs, fileConfig);
|
|
865
|
+
effectivePack = explicitPack;
|
|
866
|
+
packSource = "cli-flag";
|
|
867
|
+
} else if (explicitPack === "auto") {
|
|
868
|
+
const pages = parsed?.pages || [];
|
|
869
|
+
const landscapeCount = pages.filter((p) => p.isLandscape).length;
|
|
870
|
+
const portraitCount = pages.length - landscapeCount;
|
|
871
|
+
if (pages.length > 0 && portraitCount >= landscapeCount) {
|
|
872
|
+
pack = mergePacks(
|
|
873
|
+
resolveEffectivePack("business-brief", packs, fileConfig),
|
|
874
|
+
resolveEffectivePack("deck-and-ui", packs, fileConfig)
|
|
875
|
+
);
|
|
876
|
+
effectivePack = "business-brief+deck-and-ui";
|
|
877
|
+
packSource = "auto-pdf-portrait";
|
|
878
|
+
} else {
|
|
879
|
+
pack = resolveEffectivePack("deck-and-ui", packs, fileConfig);
|
|
880
|
+
effectivePack = "deck-and-ui";
|
|
881
|
+
packSource = "auto-pdf-landscape";
|
|
882
|
+
}
|
|
883
|
+
} else {
|
|
884
|
+
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
885
|
+
pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
886
|
+
effectivePack = packId;
|
|
887
|
+
packSource = fileConfig.pack ? "config" : "default-modality";
|
|
888
|
+
}
|
|
889
|
+
const res = auditPdfDocument(parsed, { filename: rel, pack, config: fileConfig, register });
|
|
890
|
+
const uninspectable = res.skipped.some((s) => s.file === rel);
|
|
891
|
+
return {
|
|
892
|
+
checked: !uninspectable,
|
|
893
|
+
findings: res.findings,
|
|
894
|
+
unusedSuppressions: [],
|
|
895
|
+
coverageWarnings: res.coverageWarnings || [],
|
|
896
|
+
skipped: res.skipped,
|
|
897
|
+
effectivePack,
|
|
898
|
+
packSource,
|
|
899
|
+
rulesetHash: computeRulesetHash(pack),
|
|
900
|
+
register: regInfo.register,
|
|
901
|
+
registerSource: regInfo.registerSource,
|
|
902
|
+
};
|
|
903
|
+
} catch (err) {
|
|
904
|
+
return {
|
|
905
|
+
checked: false,
|
|
906
|
+
findings: [],
|
|
907
|
+
unusedSuppressions: [],
|
|
908
|
+
coverageWarnings: [],
|
|
909
|
+
skipped: [{ file: rel, reason: `Uninspectable PDF: ${err.message}` }],
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
370
914
|
let text;
|
|
371
915
|
try {
|
|
372
916
|
text = decodeUtf8Strict(buf);
|
|
@@ -375,139 +919,557 @@ function inspectSingleFile({ absPath, rel, modality }, packs, explicitPack, conf
|
|
|
375
919
|
checked: false,
|
|
376
920
|
findings: [],
|
|
377
921
|
unusedSuppressions: [],
|
|
922
|
+
coverageWarnings: [],
|
|
378
923
|
skipped: [{ file: rel, reason: "Non-UTF-8 text encoding; convert to UTF-8 to inspect" }],
|
|
379
924
|
};
|
|
380
925
|
}
|
|
381
926
|
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
? predictPackWithPocketRouter(text).recommendedPack
|
|
385
|
-
: explicitPack === "auto"
|
|
386
|
-
? null
|
|
387
|
-
: explicitPack;
|
|
388
|
-
const packId = pickPackForFile(rel, modality, effectiveExplicit, config);
|
|
389
|
-
const pack = resolveEffectivePack(packId, packs, config);
|
|
927
|
+
const { pack, effectivePack, packSource } = resolveTextPackAndSource(text, rel, modality, explicitPack, fileConfig, packs);
|
|
928
|
+
const regInfo = resolveRegister(text, { filename: rel, flagRegister: register, config: fileConfig });
|
|
390
929
|
|
|
391
|
-
const res = auditText(text, { filename: rel, modality, pack, config });
|
|
930
|
+
const res = auditText(text, { filename: rel, modality, pack, config: fileConfig, register });
|
|
392
931
|
let findings = res.findings;
|
|
393
932
|
if (includePatterns) {
|
|
394
|
-
const patRes = auditPatterns(text, { filename: rel, modality, banks: banks || loadPatternBanks() });
|
|
395
|
-
findings = mergePatternBankFindings(findings, patRes.findings);
|
|
933
|
+
const patRes = auditPatterns(text, { filename: rel, modality, banks: banks || loadPatternBanks(), config: fileConfig });
|
|
934
|
+
findings = mergePatternBankFindings(findings, patRes.findings, { packs, pack, register: regInfo.register, config: fileConfig });
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
let profileObj = null;
|
|
938
|
+
let mlInput = null;
|
|
939
|
+
if (PROSE_ML_MODALITIES.has(modality) && (includeMl || includeProfile || text.length >= 2000 || modality === "html")) {
|
|
940
|
+
profileObj = analyzeTextProfile(text, { modality, config: fileConfig });
|
|
941
|
+
if (includeMl) {
|
|
942
|
+
mlInput = modality === "html" || modality === "svg" ? buildZones(text, modality, fileConfig).prose : text;
|
|
943
|
+
const mlRes = buildPocketMlFindings(mlInput, rel, findings, null, { profile: profileObj, modality, register: regInfo.register });
|
|
944
|
+
findings = [...findings, ...mlRes.findings];
|
|
945
|
+
}
|
|
396
946
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
947
|
+
|
|
948
|
+
const coverageWarnings = collectTextCoverageWarnings(text, modality, rel, profileObj);
|
|
949
|
+
let profileItem = null;
|
|
950
|
+
if (includeProfile && PROSE_ML_MODALITIES.has(modality)) {
|
|
951
|
+
const pocketSrc = mlInput ?? (modality === "html" || modality === "svg" ? buildZones(text, modality, fileConfig).prose : text);
|
|
952
|
+
profileItem = {
|
|
953
|
+
file: rel,
|
|
954
|
+
profile: profileObj || analyzeTextProfile(text, { modality, config: fileConfig }),
|
|
955
|
+
pocketModel: summarizePocketForProfile(pocketSrc),
|
|
956
|
+
};
|
|
400
957
|
}
|
|
401
|
-
|
|
958
|
+
|
|
959
|
+
return {
|
|
960
|
+
checked: true,
|
|
961
|
+
findings,
|
|
962
|
+
unusedSuppressions: res.unusedSuppressions,
|
|
963
|
+
coverageWarnings,
|
|
964
|
+
skipped: [],
|
|
965
|
+
effectivePack,
|
|
966
|
+
packSource,
|
|
967
|
+
rulesetHash: computeRulesetHash(pack),
|
|
968
|
+
register: regInfo.register,
|
|
969
|
+
registerSource: regInfo.registerSource,
|
|
970
|
+
profileItem,
|
|
971
|
+
_cpLineStarts: buildCodepointLineStarts(text),
|
|
972
|
+
};
|
|
402
973
|
}
|
|
403
974
|
|
|
404
975
|
// ---------- Subcommands ----------
|
|
405
976
|
|
|
406
|
-
|
|
977
|
+
const COMMAND_SPECS = {
|
|
978
|
+
check: {
|
|
979
|
+
bools: ["json", "staged", "report-unused", "profile", "ml", "patterns", "deep", "compact", "quiet", "help", "version"],
|
|
980
|
+
strings: ["pack", "register", "config", "fail-on", "format", "changed", "stdin-filename", "lang", "rule"],
|
|
981
|
+
optionalStrings: ["changed"],
|
|
982
|
+
shortBools: { q: "quiet", h: "help", v: "version" },
|
|
983
|
+
shortStrings: {},
|
|
984
|
+
usage:
|
|
985
|
+
"dislop check [paths... | -] [--pack <id|auto>] [--register <id|auto>] [--deep] [--compact] [--profile] [--ml] [--patterns]\n" +
|
|
986
|
+
" [--fail-on error|warning|info|never] [--format text|json|agent|sarif|github|md]\n" +
|
|
987
|
+
" [--changed [ref] | --staged] [--rule <id,...>] [--stdin-filename <name>]\n" +
|
|
988
|
+
" [--report-unused] [--config <path>] [-q|--quiet] [--lang en|zh]",
|
|
989
|
+
summary: "Audit files, directories, or stdin for AI artifacts, clichés, and template layouts (0 network calls).",
|
|
990
|
+
examples: [
|
|
991
|
+
"dislop check .",
|
|
992
|
+
"dislop check draft.md --deep --lang zh",
|
|
993
|
+
"dislop check draft.md --register argumentative --format agent",
|
|
994
|
+
"dislop check --changed=origin/main --format github",
|
|
995
|
+
],
|
|
996
|
+
},
|
|
997
|
+
verify: {
|
|
998
|
+
bools: ["allow-added", "strict", "staged", "json", "help", "version"],
|
|
999
|
+
strings: ["pack", "register", "git", "keep", "format", "lang", "stdin-filename", "config"],
|
|
1000
|
+
optionalStrings: ["git"],
|
|
1001
|
+
shortBools: { h: "help", v: "version" },
|
|
1002
|
+
shortStrings: {},
|
|
1003
|
+
usage: "dislop verify (<before> <after> | --git [ref] <file>) [--keep a,b] [--pack <id|auto>] [--register <name>] [--allow-added] [--strict] [--lang en|zh] [--json]",
|
|
1004
|
+
summary: "Verify a revised draft retains numbers, qualifiers, keep terms, and introduces zero new AI slop.",
|
|
1005
|
+
examples: [
|
|
1006
|
+
"dislop verify --git HEAD draft.md",
|
|
1007
|
+
"dislop verify before.md after.md --keep latency,SLA --strict --json",
|
|
1008
|
+
],
|
|
1009
|
+
},
|
|
1010
|
+
explain: {
|
|
1011
|
+
bools: ["json", "help", "version"],
|
|
1012
|
+
strings: ["lang", "format"],
|
|
1013
|
+
optionalStrings: [],
|
|
1014
|
+
shortBools: { h: "help", v: "version" },
|
|
1015
|
+
shortStrings: {},
|
|
1016
|
+
usage: "dislop explain <rule-id> [--lang en|zh] [--format text|json] [--json]",
|
|
1017
|
+
summary: "Show rationale, deletion test, and bad/trap/good examples for a rule or pattern ID.",
|
|
1018
|
+
examples: ["dislop explain negation-pivot-frame --lang zh", "dislop explain chatbot-artifact --json"],
|
|
1019
|
+
},
|
|
1020
|
+
packs: {
|
|
1021
|
+
bools: ["json", "help", "version"],
|
|
1022
|
+
strings: ["format"],
|
|
1023
|
+
optionalStrings: [],
|
|
1024
|
+
shortBools: { h: "help", v: "version" },
|
|
1025
|
+
shortStrings: {},
|
|
1026
|
+
usage: "dislop packs [--format text|json] [--json]",
|
|
1027
|
+
summary: "List bundled rule packs and supported file types.",
|
|
1028
|
+
examples: ["dislop packs", "dislop packs --json"],
|
|
1029
|
+
},
|
|
1030
|
+
catalog: {
|
|
1031
|
+
bools: ["json", "no-exemplars", "help", "version"],
|
|
1032
|
+
strings: ["query", "pack", "category", "dimension", "family", "modality", "severity", "tier", "lang", "format", "limit"],
|
|
1033
|
+
optionalStrings: [],
|
|
1034
|
+
shortBools: { h: "help", v: "version" },
|
|
1035
|
+
shortStrings: {},
|
|
1036
|
+
usage:
|
|
1037
|
+
"dislop catalog [query] [--pack <id>] [--category <cat>] [--dimension <dim>] [--family <prefix>]\n" +
|
|
1038
|
+
" [--modality <mod>] [--severity <sev>] [--tier invariant|taste] [--limit <n>]\n" +
|
|
1039
|
+
" [--no-exemplars] [--format text|json|md] [--lang en|zh]",
|
|
1040
|
+
summary: "Search and filter dislop's 53-rule AI-slop catalog.",
|
|
1041
|
+
examples: ["dislop catalog negation --lang zh", "dislop catalog --pack deck-and-ui --format md"],
|
|
1042
|
+
},
|
|
1043
|
+
patterns: {
|
|
1044
|
+
bools: ["json", "help", "version"],
|
|
1045
|
+
strings: ["stdin-filename", "angle", "lang", "format"],
|
|
1046
|
+
optionalStrings: [],
|
|
1047
|
+
shortBools: { h: "help", v: "version" },
|
|
1048
|
+
shortStrings: {},
|
|
1049
|
+
usage: "dislop patterns [file | -] [--stdin-filename <name>] [--angle <a,b>] [--lang en|zh] [--json]",
|
|
1050
|
+
summary: "Run multi-angle extended pattern-bank scan and profile.",
|
|
1051
|
+
examples: ["dislop patterns draft.md --lang zh", "cat draft.md | dislop patterns - --json"],
|
|
1052
|
+
},
|
|
1053
|
+
voice: {
|
|
1054
|
+
bools: ["json", "help", "version"],
|
|
1055
|
+
strings: ["output", "lang", "format"],
|
|
1056
|
+
optionalStrings: [],
|
|
1057
|
+
shortBools: { h: "help", v: "version" },
|
|
1058
|
+
shortStrings: { o: "output" },
|
|
1059
|
+
usage: "dislop voice [paths... | -] [--output|-o <voice.json>] [--lang auto|en|zh] [--json]",
|
|
1060
|
+
summary: "Extract an offline deterministic dislop.voice/1 writing profile (0 network calls).",
|
|
1061
|
+
examples: ["dislop voice notes/*.md -o voice.json", "dislop voice essays.md --lang zh --json"],
|
|
1062
|
+
},
|
|
1063
|
+
model: {
|
|
1064
|
+
bools: ["force", "dry-run", "yes", "no-copy", "allow-lan", "no-loopback", "json", "help", "version"],
|
|
1065
|
+
strings: ["tier", "provider", "sha256", "cache-dir", "threshold", "stdin-filename", "pack", "config", "endpoint", "model", "output", "format", "lang"],
|
|
1066
|
+
optionalStrings: [],
|
|
1067
|
+
shortBools: { h: "help", v: "version" },
|
|
1068
|
+
shortStrings: { o: "output" },
|
|
1069
|
+
usage: "dislop model [status|score|install|import|remove|deslop] [target] [--tier <t>] [--lang en|zh] [--json]",
|
|
1070
|
+
summary: "Inspect bundled 14.6 KB Pocket ML, hardware fit, and manage optional local models.",
|
|
1071
|
+
examples: ["dislop model status --lang zh", "dislop model score draft.md --json"],
|
|
1072
|
+
},
|
|
1073
|
+
setup: {
|
|
1074
|
+
bools: ["force", "dry-run", "yes", "json", "help", "version"],
|
|
1075
|
+
strings: ["tier", "provider", "cache-dir", "format", "lang"],
|
|
1076
|
+
optionalStrings: [],
|
|
1077
|
+
shortBools: { h: "help", v: "version" },
|
|
1078
|
+
shortStrings: {},
|
|
1079
|
+
usage: "dislop setup [--tier auto|none|fast|balanced|quality] [--dry-run] [--force] [--lang en|zh]",
|
|
1080
|
+
summary: "Interactive or flag-driven optional local GGUF model setup.",
|
|
1081
|
+
examples: ["dislop setup --dry-run", "dislop setup --tier fast --yes"],
|
|
1082
|
+
},
|
|
1083
|
+
deslop: {
|
|
1084
|
+
bools: ["local", "allow-lan", "json", "help", "version"],
|
|
1085
|
+
strings: ["pack", "register", "config", "stdin-filename", "endpoint", "model", "output", "format", "lang"],
|
|
1086
|
+
optionalStrings: [],
|
|
1087
|
+
shortBools: { h: "help", v: "version" },
|
|
1088
|
+
shortStrings: { o: "output" },
|
|
1089
|
+
usage: "dislop deslop [file | -] --local [--pack <id|auto>] [--register <name>] [--endpoint <url>] [--model <id>] [--output|-o <file>] [--json]",
|
|
1090
|
+
summary: "Fact-locked paragraph cleanup using a local loopback model (--local).",
|
|
1091
|
+
examples: ["dislop deslop draft.md --local -o clean.md"],
|
|
1092
|
+
},
|
|
1093
|
+
resources: {
|
|
1094
|
+
bools: ["json", "help", "version"],
|
|
1095
|
+
strings: ["format"],
|
|
1096
|
+
optionalStrings: [],
|
|
1097
|
+
shortBools: { h: "help", v: "version" },
|
|
1098
|
+
shortStrings: {},
|
|
1099
|
+
usage: "dislop resources [--format text|json] [--json]",
|
|
1100
|
+
summary: "Show bundled offline packs, static agent links, and Official Cloud MCP details.",
|
|
1101
|
+
examples: ["dislop resources", "dislop resources --json"],
|
|
1102
|
+
},
|
|
1103
|
+
"pack-test": {
|
|
1104
|
+
bools: ["help", "version"],
|
|
1105
|
+
strings: [],
|
|
1106
|
+
optionalStrings: [],
|
|
1107
|
+
shortBools: { h: "help", v: "version" },
|
|
1108
|
+
shortStrings: {},
|
|
1109
|
+
usage: "dislop pack-test",
|
|
1110
|
+
summary: "Validate Pack Schema v2 manifests and embedded hit/clean fixture assertions.",
|
|
1111
|
+
examples: ["dislop pack-test"],
|
|
1112
|
+
},
|
|
1113
|
+
init: {
|
|
1114
|
+
bools: ["help", "version"],
|
|
1115
|
+
strings: [],
|
|
1116
|
+
optionalStrings: [],
|
|
1117
|
+
shortBools: { h: "help", v: "version" },
|
|
1118
|
+
shortStrings: {},
|
|
1119
|
+
usage: "dislop init",
|
|
1120
|
+
summary: "Create starter .dislop.json config and ensure .dislop.local.json is gitignored.",
|
|
1121
|
+
examples: ["dislop init"],
|
|
1122
|
+
},
|
|
1123
|
+
review: {
|
|
1124
|
+
bools: ["offline", "compact", "dry-run", "print-prompt", "yes", "include-notes", "include-hidden", "json", "help", "version"],
|
|
1125
|
+
strings: ["endpoint", "api-key-env", "provider", "model", "base-url", "pack", "register", "format", "lang", "fail-on", "timeout", "max-chunks", "stdin-filename", "config"],
|
|
1126
|
+
optionalStrings: [],
|
|
1127
|
+
shortBools: { y: "yes", h: "help", v: "version" },
|
|
1128
|
+
shortStrings: {},
|
|
1129
|
+
usage:
|
|
1130
|
+
"dislop review [file | -] [--offline | --endpoint <url> | --provider openai|gemini|openrouter|compatible|local]\n" +
|
|
1131
|
+
" [--model <id>] [--base-url <url>] [--pack <id|auto>] [--register <id|auto>]\n" +
|
|
1132
|
+
" [--dry-run] [--print-prompt] [--yes] [--format text|json|agent] [--lang en|zh]",
|
|
1133
|
+
summary: "Multi-layer editorial review (offline rubric preflight or explicit opt-in BYOK LLM review).",
|
|
1134
|
+
examples: [
|
|
1135
|
+
"dislop review draft.md --offline --lang zh",
|
|
1136
|
+
"dislop review draft.md --provider openai --dry-run",
|
|
1137
|
+
"dislop review draft.md --provider gemini --model gemini-3.1-flash-lite-preview --yes",
|
|
1138
|
+
],
|
|
1139
|
+
},
|
|
1140
|
+
doctor: {
|
|
1141
|
+
bools: ["online", "no-loopback", "json", "help", "version"],
|
|
1142
|
+
strings: ["cache-dir", "format", "lang"],
|
|
1143
|
+
optionalStrings: [],
|
|
1144
|
+
shortBools: { h: "help", v: "version" },
|
|
1145
|
+
shortStrings: {},
|
|
1146
|
+
usage: "dislop doctor [--online] [--no-loopback] [--lang en|zh] [--json]",
|
|
1147
|
+
summary: "Check 3-layer readiness (Skill, Local CLI + Pocket ML + local runners, BYOK review env, and optional --online Cloud MCP ping).",
|
|
1148
|
+
examples: ["dislop doctor", "dislop doctor --lang zh --json", "dislop doctor --online"],
|
|
1149
|
+
},
|
|
1150
|
+
};
|
|
1151
|
+
COMMAND_SPECS.search = COMMAND_SPECS.catalog;
|
|
1152
|
+
|
|
1153
|
+
function levenshtein(a, b) {
|
|
1154
|
+
const m = a.length;
|
|
1155
|
+
const n = b.length;
|
|
1156
|
+
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
|
1157
|
+
for (let i = 0; i <= m; i += 1) dp[i][0] = i;
|
|
1158
|
+
for (let j = 0; j <= n; j += 1) dp[0][j] = j;
|
|
1159
|
+
for (let i = 1; i <= m; i += 1) {
|
|
1160
|
+
for (let j = 1; j <= n; j += 1) {
|
|
1161
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
1162
|
+
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
return dp[m][n];
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
function closestFlagSuggestion(unknown, knownFlags) {
|
|
1169
|
+
let best = null;
|
|
1170
|
+
let bestDist = 4;
|
|
1171
|
+
for (const cand of knownFlags) {
|
|
1172
|
+
const d = levenshtein(unknown, cand);
|
|
1173
|
+
if (d < bestDist) {
|
|
1174
|
+
bestDist = d;
|
|
1175
|
+
best = cand;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
return best ? ` Did you mean '--${best}'?` : "";
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
function printSubcommandHelp(cmdName) {
|
|
1182
|
+
const spec = COMMAND_SPECS[cmdName];
|
|
1183
|
+
if (!spec) {
|
|
1184
|
+
printHelp();
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
console.log(`dislop ${cmdName} — ${spec.summary}\n`);
|
|
1188
|
+
console.log(`Usage:\n ${spec.usage}`);
|
|
1189
|
+
if (spec.examples?.length) {
|
|
1190
|
+
console.log(`\nExamples:\n${spec.examples.map((ex) => ` ${ex}`).join("\n")}`);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
function shouldUseColor() {
|
|
1195
|
+
if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== "0") return true;
|
|
1196
|
+
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== "") return false;
|
|
1197
|
+
return Boolean(process.stdout.isTTY);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
function colorizeTextReport(text, useColor) {
|
|
1201
|
+
if (!useColor || !text) return text;
|
|
1202
|
+
const RESET = "\x1b[0m";
|
|
1203
|
+
const RED = "\x1b[31m";
|
|
1204
|
+
const YELLOW = "\x1b[33m";
|
|
1205
|
+
const CYAN = "\x1b[36m";
|
|
1206
|
+
const DIM = "\x1b[2m";
|
|
1207
|
+
const GREEN = "\x1b[32m";
|
|
1208
|
+
return text
|
|
1209
|
+
.split("\n")
|
|
1210
|
+
.map((line) => {
|
|
1211
|
+
if (line.startsWith(" [ERROR]") || line.startsWith(" [硬伤]")) {
|
|
1212
|
+
return line.replace(/^(\s*\[(?:ERROR|硬伤)\])/, `${RED}$1${RESET}`);
|
|
1213
|
+
}
|
|
1214
|
+
if (line.startsWith(" [WARNING]") || line.startsWith(" [提醒]")) {
|
|
1215
|
+
return line.replace(/^(\s*\[(?:WARNING|提醒)\])/, `${YELLOW}$1${RESET}`);
|
|
1216
|
+
}
|
|
1217
|
+
if (line.startsWith(" [INFO]") || line.startsWith(" [提示]")) {
|
|
1218
|
+
return line.replace(/^(\s*\[(?:INFO|提示)\])/, `${CYAN}$1${RESET}`);
|
|
1219
|
+
}
|
|
1220
|
+
if (
|
|
1221
|
+
line.startsWith(" [SKIP]") ||
|
|
1222
|
+
line.startsWith(" [跳过]") ||
|
|
1223
|
+
line.startsWith(" [UNUSED]") ||
|
|
1224
|
+
line.startsWith(" [失效豁免]") ||
|
|
1225
|
+
line.startsWith(" [COVERAGE]") ||
|
|
1226
|
+
line.startsWith(" [覆盖提示]")
|
|
1227
|
+
) {
|
|
1228
|
+
return `${DIM}${line}${RESET}`;
|
|
1229
|
+
}
|
|
1230
|
+
if (line.startsWith("dislop: no known patterns found") || line.startsWith("dislop: 未发现已知模式")) {
|
|
1231
|
+
return `${GREEN}${line}${RESET}`;
|
|
1232
|
+
}
|
|
1233
|
+
return line;
|
|
1234
|
+
})
|
|
1235
|
+
.join("\n");
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function parseFlags(args, cmdName = null) {
|
|
1239
|
+
const spec = cmdName ? COMMAND_SPECS[cmdName] : null;
|
|
1240
|
+
const boolSet = new Set(spec ? spec.bools : [
|
|
1241
|
+
"json", "staged", "report-unused", "no-loopback", "help", "version", "mcp",
|
|
1242
|
+
"no-exemplars", "profile", "ml", "patterns", "deep", "compact", "quiet", "force",
|
|
1243
|
+
"dry-run", "yes", "no-copy", "local", "allow-lan", "offline", "allow-added", "strict",
|
|
1244
|
+
]);
|
|
1245
|
+
const stringSet = spec ? new Set(spec.strings) : null;
|
|
1246
|
+
const optionalSet = new Set(spec ? spec.optionalStrings : ["changed", "git"]);
|
|
1247
|
+
const shortBools = spec ? spec.shortBools : { h: "help", v: "version", q: "quiet" };
|
|
1248
|
+
const shortStrings = spec ? spec.shortStrings : { o: "output" };
|
|
1249
|
+
const allKnown = spec ? [...spec.bools, ...spec.strings] : [];
|
|
1250
|
+
|
|
1251
|
+
for (const a of args) {
|
|
1252
|
+
if (a === "--") break;
|
|
1253
|
+
if (a === "-h" || a === "--help") {
|
|
1254
|
+
return { flags: { help: true }, positional: [] };
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
|
|
407
1258
|
const flags = {};
|
|
408
1259
|
const positional = [];
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
"report-unused",
|
|
413
|
-
"no-loopback",
|
|
414
|
-
"help",
|
|
415
|
-
"version",
|
|
416
|
-
"mcp",
|
|
417
|
-
"no-exemplars",
|
|
418
|
-
"profile",
|
|
419
|
-
"ml",
|
|
420
|
-
"patterns",
|
|
421
|
-
"force",
|
|
422
|
-
"dry-run",
|
|
423
|
-
"yes",
|
|
424
|
-
"no-copy",
|
|
425
|
-
"local",
|
|
426
|
-
"allow-lan",
|
|
427
|
-
]);
|
|
1260
|
+
let endOfFlags = false;
|
|
1261
|
+
const cwd = process.cwd();
|
|
1262
|
+
|
|
428
1263
|
for (let i = 0; i < args.length; i += 1) {
|
|
429
1264
|
const arg = args[i];
|
|
1265
|
+
if (endOfFlags) {
|
|
1266
|
+
positional.push(arg);
|
|
1267
|
+
continue;
|
|
1268
|
+
}
|
|
1269
|
+
if (arg === "--") {
|
|
1270
|
+
endOfFlags = true;
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
430
1273
|
if (arg === "-") {
|
|
431
1274
|
positional.push("-");
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
if (
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
} else {
|
|
441
|
-
console.error("dislop: flag '-o' requires a file path");
|
|
1275
|
+
continue;
|
|
1276
|
+
}
|
|
1277
|
+
if (arg.startsWith("--")) {
|
|
1278
|
+
const eq = arg.indexOf("=");
|
|
1279
|
+
const key = eq !== -1 ? arg.slice(2, eq) : arg.slice(2);
|
|
1280
|
+
if (spec && !boolSet.has(key) && !stringSet.has(key)) {
|
|
1281
|
+
const hint = closestFlagSuggestion(key, allKnown);
|
|
1282
|
+
console.error(`dislop ${cmdName}: unknown flag '--${key}'.${hint} Run 'dislop ${cmdName} --help'.`);
|
|
442
1283
|
process.exit(2);
|
|
443
1284
|
}
|
|
444
|
-
} else if (arg.startsWith("-o=")) {
|
|
445
|
-
flags.output = arg.slice(3);
|
|
446
|
-
} else if (arg.startsWith("--")) {
|
|
447
|
-
const eq = arg.indexOf("=");
|
|
448
1285
|
if (eq !== -1) {
|
|
449
|
-
const key = arg.slice(2, eq);
|
|
450
1286
|
const val = arg.slice(eq + 1);
|
|
451
|
-
if (
|
|
1287
|
+
if (boolSet.has(key)) {
|
|
452
1288
|
const low = val.trim().toLowerCase();
|
|
453
|
-
if (low === "true" || low === "1" || low === "yes")
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
flags[key] = false;
|
|
457
|
-
} else {
|
|
1289
|
+
if (low === "true" || low === "1" || low === "yes") flags[key] = true;
|
|
1290
|
+
else if (low === "false" || low === "0" || low === "no") flags[key] = false;
|
|
1291
|
+
else {
|
|
458
1292
|
console.error(`dislop: flag '--${key}' does not accept value '${val}'`);
|
|
459
1293
|
process.exit(2);
|
|
460
1294
|
}
|
|
1295
|
+
} else if (optionalSet.has(key) && val === "") {
|
|
1296
|
+
flags[key] = "HEAD";
|
|
461
1297
|
} else {
|
|
462
1298
|
flags[key] = val;
|
|
463
1299
|
}
|
|
464
|
-
} else {
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
1300
|
+
} else if (boolSet.has(key)) {
|
|
1301
|
+
flags[key] = true;
|
|
1302
|
+
} else if (optionalSet.has(key)) {
|
|
1303
|
+
const next = args[i + 1];
|
|
1304
|
+
if (i + 1 >= args.length || next === "-" || next.startsWith("-")) {
|
|
1305
|
+
flags[key] = "HEAD";
|
|
1306
|
+
} else if ((key === "changed" || key === "git") && fs.existsSync(path.resolve(cwd, next))) {
|
|
469
1307
|
flags[key] = "HEAD";
|
|
1308
|
+
} else {
|
|
1309
|
+
flags[key] = next;
|
|
1310
|
+
i += 1;
|
|
1311
|
+
}
|
|
1312
|
+
} else if (i + 1 < args.length) {
|
|
1313
|
+
const next = args[i + 1];
|
|
1314
|
+
if (next.length > 1 && next.startsWith("-")) {
|
|
1315
|
+
console.error(`dislop: flag '--${key}' requires a value (got '${next}')`);
|
|
1316
|
+
process.exit(2);
|
|
1317
|
+
}
|
|
1318
|
+
flags[key] = next;
|
|
1319
|
+
i += 1;
|
|
1320
|
+
} else {
|
|
1321
|
+
console.error(`dislop: flag '--${key}' requires a value`);
|
|
1322
|
+
process.exit(2);
|
|
1323
|
+
}
|
|
1324
|
+
} else if (arg.startsWith("-") && arg.length > 1) {
|
|
1325
|
+
const eq = arg.indexOf("=");
|
|
1326
|
+
const shortKey = eq !== -1 ? arg.slice(1, eq) : arg.slice(1);
|
|
1327
|
+
if (shortBools[shortKey] && eq === -1) {
|
|
1328
|
+
flags[shortBools[shortKey]] = true;
|
|
1329
|
+
} else if (shortStrings[shortKey]) {
|
|
1330
|
+
if (eq !== -1) {
|
|
1331
|
+
flags[shortStrings[shortKey]] = arg.slice(eq + 1);
|
|
470
1332
|
} else if (i + 1 < args.length) {
|
|
471
|
-
|
|
1333
|
+
const next = args[i + 1];
|
|
1334
|
+
if (next.length > 1 && next.startsWith("-")) {
|
|
1335
|
+
console.error(`dislop: flag '-${shortKey}' requires a value (got '${next}')`);
|
|
1336
|
+
process.exit(2);
|
|
1337
|
+
}
|
|
1338
|
+
flags[shortStrings[shortKey]] = next;
|
|
472
1339
|
i += 1;
|
|
473
1340
|
} else {
|
|
474
|
-
|
|
1341
|
+
console.error(`dislop: flag '-${shortKey}' requires a value`);
|
|
1342
|
+
process.exit(2);
|
|
475
1343
|
}
|
|
1344
|
+
} else if (shortKey.length > 1 && eq === -1 && [...shortKey].every((ch) => shortBools[ch])) {
|
|
1345
|
+
for (const ch of shortKey) flags[shortBools[ch]] = true;
|
|
1346
|
+
} else {
|
|
1347
|
+
console.error(`dislop${cmdName ? ` ${cmdName}` : ""}: unknown flag '${arg}'. Run 'dislop${cmdName ? ` ${cmdName}` : ""} --help'.`);
|
|
1348
|
+
process.exit(2);
|
|
476
1349
|
}
|
|
477
1350
|
} else {
|
|
478
1351
|
positional.push(arg);
|
|
479
1352
|
}
|
|
480
1353
|
}
|
|
481
|
-
if (flags.help) {
|
|
1354
|
+
if (!spec && flags.help) {
|
|
482
1355
|
printHelp();
|
|
483
1356
|
process.exit(0);
|
|
484
1357
|
}
|
|
485
1358
|
return { flags, positional };
|
|
486
1359
|
}
|
|
487
1360
|
|
|
488
|
-
function
|
|
489
|
-
|
|
490
|
-
|
|
1361
|
+
function readStdinTextChecked(cmdLabel = "check") {
|
|
1362
|
+
const buf = fs.readFileSync(0);
|
|
1363
|
+
if (buf.length >= 4 && buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04) {
|
|
1364
|
+
console.error(`dislop ${cmdLabel}: stdin looks like binary ZIP/OOXML (.docx/.pptx); pass the file path instead (e.g., 'dislop ${cmdLabel} deck.pptx').`);
|
|
1365
|
+
process.exit(2);
|
|
1366
|
+
}
|
|
1367
|
+
try {
|
|
1368
|
+
return decodeUtf8Strict(buf);
|
|
1369
|
+
} catch {
|
|
1370
|
+
console.error(`dislop ${cmdLabel}: stdin is not valid UTF-8 text; convert to UTF-8 or pass a supported file path.`);
|
|
491
1371
|
process.exit(2);
|
|
492
1372
|
}
|
|
493
1373
|
}
|
|
494
1374
|
|
|
495
|
-
function
|
|
496
|
-
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
1375
|
+
function detectStdinFilename(rawText, explicitName) {
|
|
1376
|
+
if (explicitName) return explicitName;
|
|
1377
|
+
const head = String(rawText || "").replace(/^\ufeff/, "").trimStart().slice(0, 128).toLowerCase();
|
|
1378
|
+
if (head.startsWith("<!doctype html") || head.startsWith("<html")) {
|
|
1379
|
+
return "stdin.html";
|
|
1380
|
+
}
|
|
1381
|
+
return "stdin.md";
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
function collectKnownRuleIds(packs, banks = null) {
|
|
1385
|
+
const known = new Set(["pocket-stealth-vapor"]);
|
|
1386
|
+
for (const p of Object.values(packs || {})) {
|
|
1387
|
+
for (const r of p.rules || []) {
|
|
1388
|
+
if (r.id) known.add(r.id);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
const loadedBanks = banks || loadPatternBanks();
|
|
1392
|
+
for (const bank of Object.values(loadedBanks || {})) {
|
|
1393
|
+
for (const pat of bank.patterns || []) {
|
|
1394
|
+
if (pat.ruleId) known.add(pat.ruleId);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const patLib = loadPatternLibrary();
|
|
1398
|
+
for (const rid of Object.keys(patLib)) known.add(rid);
|
|
1399
|
+
return known;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
function assertTextOrJsonFormat(format) {
|
|
1403
|
+
if (!["text", "json"].includes(format)) {
|
|
1404
|
+
console.error(`dislop: invalid --format '${format}' (expected text or json)`);
|
|
1405
|
+
process.exit(2);
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
function applyCompactReport(report) {
|
|
1410
|
+
const ruleMeta = {};
|
|
1411
|
+
const compactFindings = [];
|
|
1412
|
+
for (const f of report.findings || []) {
|
|
1413
|
+
const rid = f.ruleId;
|
|
1414
|
+
const strategy = f.fixStrategy || deriveFixStrategy({ id: rid, family: f.family });
|
|
1415
|
+
if (!ruleMeta[rid]) {
|
|
1416
|
+
ruleMeta[rid] = {
|
|
1417
|
+
tier: f.tier || "taste",
|
|
1418
|
+
family: f.family || "general",
|
|
1419
|
+
fixStrategy: strategy,
|
|
1420
|
+
message: f.message,
|
|
1421
|
+
...(f.deletionTest ? { deletionTest: f.deletionTest } : {}),
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
compactFindings.push({
|
|
1425
|
+
fingerprint: f.fingerprint,
|
|
1426
|
+
ruleId: rid,
|
|
1427
|
+
severity: f.severity,
|
|
1428
|
+
fixStrategy: strategy,
|
|
1429
|
+
file: f.file,
|
|
1430
|
+
modality: f.modality,
|
|
1431
|
+
location: f.location,
|
|
1432
|
+
line: f.line,
|
|
1433
|
+
col: f.col,
|
|
1434
|
+
...(f.span ? { span: f.span } : {}),
|
|
1435
|
+
match: f.match,
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
return {
|
|
1439
|
+
...report,
|
|
1440
|
+
compact: true,
|
|
1441
|
+
ruleMeta,
|
|
1442
|
+
findings: compactFindings,
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
function runCheck(args, packs) {
|
|
1447
|
+
const { flags, positional } = parseFlags(args, "check");
|
|
1448
|
+
if (flags.help) {
|
|
1449
|
+
printSubcommandHelp("check");
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
const cwd = process.cwd();
|
|
1453
|
+
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
1454
|
+
const format = flags.json ? "json" : flags.format || "text";
|
|
1455
|
+
const failOn = flags["fail-on"] || config.failOn || "error";
|
|
1456
|
+
const lang = flags.lang || "en";
|
|
1457
|
+
if (!["en", "zh"].includes(lang)) {
|
|
1458
|
+
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
1459
|
+
process.exit(2);
|
|
1460
|
+
}
|
|
502
1461
|
const reportUnused = Boolean(flags["report-unused"]);
|
|
503
|
-
const
|
|
504
|
-
const
|
|
505
|
-
const
|
|
1462
|
+
const quiet = Boolean(flags.quiet);
|
|
1463
|
+
const useColor = format === "text" && shouldUseColor();
|
|
1464
|
+
const includeProfile = Boolean(flags.profile || flags.deep);
|
|
1465
|
+
const includeMl = Boolean(flags.ml || flags.deep);
|
|
1466
|
+
const includePatterns = Boolean(flags.patterns || flags.deep);
|
|
1467
|
+
const compactJson = Boolean(flags.compact && format === "json");
|
|
506
1468
|
const banks = includePatterns ? loadPatternBanks() : null;
|
|
507
1469
|
|
|
508
|
-
const validFormats = new Set(["text", "json", "sarif", "github", "md"]);
|
|
1470
|
+
const validFormats = new Set(["text", "json", "agent", "sarif", "github", "md"]);
|
|
509
1471
|
if (!validFormats.has(format)) {
|
|
510
|
-
console.error(`dislop: invalid --format '${format}' (expected text, json, sarif, github, or md)`);
|
|
1472
|
+
console.error(`dislop: invalid --format '${format}' (expected text, json, agent, sarif, github, or md)`);
|
|
511
1473
|
process.exit(2);
|
|
512
1474
|
}
|
|
513
1475
|
if (!SEVERITY_RANK[failOn]) {
|
|
@@ -515,56 +1477,127 @@ function runCheck(args, packs) {
|
|
|
515
1477
|
process.exit(2);
|
|
516
1478
|
}
|
|
517
1479
|
|
|
1480
|
+
let flagRegister = null;
|
|
1481
|
+
if (flags.register !== undefined) {
|
|
1482
|
+
const norm = String(flags.register).trim().toLowerCase();
|
|
1483
|
+
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
1484
|
+
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
1485
|
+
process.exit(2);
|
|
1486
|
+
}
|
|
1487
|
+
flagRegister = norm;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
let ruleFilter = null;
|
|
1491
|
+
if (flags.rule !== undefined) {
|
|
1492
|
+
const requested = String(flags.rule)
|
|
1493
|
+
.split(",")
|
|
1494
|
+
.map((s) => s.trim())
|
|
1495
|
+
.filter(Boolean);
|
|
1496
|
+
if (requested.length === 0) {
|
|
1497
|
+
console.error("dislop check: '--rule' requires at least one rule ID");
|
|
1498
|
+
process.exit(2);
|
|
1499
|
+
}
|
|
1500
|
+
const known = collectKnownRuleIds(packs, banks);
|
|
1501
|
+
const unknown = requested.filter((r) => !known.has(r));
|
|
1502
|
+
if (unknown.length > 0) {
|
|
1503
|
+
console.error(`dislop check: unknown rule ID(s): ${unknown.join(", ")}. Run 'dislop catalog' to list valid rule IDs.`);
|
|
1504
|
+
process.exit(2);
|
|
1505
|
+
}
|
|
1506
|
+
ruleFilter = new Set(requested);
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
if (flags.pack && flags.pack !== "auto" && !packs[flags.pack]) {
|
|
1510
|
+
console.error(`dislop: unknown pack '${flags.pack}' (available: auto, ${Object.keys(packs).join(", ")})`);
|
|
1511
|
+
process.exit(2);
|
|
1512
|
+
}
|
|
1513
|
+
|
|
518
1514
|
// Stdin mode
|
|
519
1515
|
if (positional.includes("-")) {
|
|
520
|
-
const stdinText =
|
|
521
|
-
const filename = flags["stdin-filename"]
|
|
1516
|
+
const stdinText = readStdinTextChecked("check");
|
|
1517
|
+
const filename = detectStdinFilename(stdinText, flags["stdin-filename"]);
|
|
522
1518
|
const modality = detectModality(filename) || "markdown";
|
|
523
|
-
const
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
: flags.pack === "auto"
|
|
527
|
-
? null
|
|
528
|
-
: flags.pack || null;
|
|
529
|
-
const packId = pickPackForFile(filename, modality, effectiveExplicit, config);
|
|
530
|
-
let pack;
|
|
1519
|
+
const fileConfig = resolveConfigForFile(filename, config);
|
|
1520
|
+
let resolved;
|
|
1521
|
+
let regInfo;
|
|
531
1522
|
try {
|
|
532
|
-
|
|
1523
|
+
resolved = resolveTextPackAndSource(stdinText, filename, modality, flags.pack || null, fileConfig, packs);
|
|
1524
|
+
regInfo = resolveRegister(stdinText, { filename, flagRegister, config: fileConfig });
|
|
533
1525
|
} catch (err) {
|
|
534
1526
|
console.error(`dislop: ${err.message}`);
|
|
535
1527
|
process.exit(2);
|
|
536
1528
|
}
|
|
537
|
-
const
|
|
1529
|
+
const { pack, effectivePack, packSource } = resolved;
|
|
1530
|
+
const res = auditText(stdinText, { filename, modality, pack, config: fileConfig, register: flagRegister });
|
|
538
1531
|
let findings = res.findings;
|
|
539
1532
|
if (includePatterns) {
|
|
540
|
-
const patRes = auditPatterns(stdinText, { filename, modality, banks });
|
|
541
|
-
findings = mergePatternBankFindings(findings, patRes.findings
|
|
1533
|
+
const patRes = auditPatterns(stdinText, { filename, modality, banks, config: fileConfig });
|
|
1534
|
+
findings = mergePatternBankFindings(findings, patRes.findings, {
|
|
1535
|
+
packs,
|
|
1536
|
+
pack,
|
|
1537
|
+
register: regInfo.register,
|
|
1538
|
+
config: fileConfig,
|
|
1539
|
+
});
|
|
542
1540
|
}
|
|
543
|
-
|
|
544
|
-
|
|
1541
|
+
let profileObj = null;
|
|
1542
|
+
let mlInput = null;
|
|
1543
|
+
if (PROSE_ML_MODALITIES.has(modality) && (includeMl || includeProfile || stdinText.length >= 2000 || modality === "html")) {
|
|
1544
|
+
profileObj = analyzeTextProfile(stdinText, { modality, config: fileConfig });
|
|
1545
|
+
if (includeMl) {
|
|
1546
|
+
mlInput = modality === "html" || modality === "svg" ? buildZones(stdinText, modality, fileConfig).prose : stdinText;
|
|
1547
|
+
findings = [
|
|
1548
|
+
...findings,
|
|
1549
|
+
...buildPocketMlFindings(mlInput, filename, findings, null, {
|
|
1550
|
+
profile: profileObj,
|
|
1551
|
+
modality,
|
|
1552
|
+
register: regInfo.register,
|
|
1553
|
+
}).findings,
|
|
1554
|
+
];
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
if (ruleFilter) {
|
|
1558
|
+
findings = findings.filter((f) => ruleFilter.has(f.ruleId));
|
|
545
1559
|
}
|
|
1560
|
+
const triggered =
|
|
1561
|
+
findings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
|
|
1562
|
+
(reportUnused && res.unusedSuppressions.length > 0);
|
|
1563
|
+
const outFindings = quiet
|
|
1564
|
+
? findings.filter((f) => (SEVERITY_RANK[f.severity] || 1) >= SEVERITY_RANK[failOn])
|
|
1565
|
+
: findings;
|
|
1566
|
+
const coverageWarnings = collectTextCoverageWarnings(stdinText, modality, filename, profileObj);
|
|
1567
|
+
const pocketSrc = includeProfile && PROSE_ML_MODALITIES.has(modality)
|
|
1568
|
+
? mlInput ?? (modality === "html" || modality === "svg" ? buildZones(stdinText, modality, fileConfig).prose : stdinText)
|
|
1569
|
+
: null;
|
|
546
1570
|
const report = {
|
|
547
1571
|
version: ENGINE_VERSION,
|
|
1572
|
+
context: { register: regInfo.register, registerSource: regInfo.registerSource },
|
|
1573
|
+
rulesetHash: computeRulesetHash(pack),
|
|
1574
|
+
effectivePack,
|
|
1575
|
+
packSource,
|
|
1576
|
+
changedFilter: false,
|
|
1577
|
+
files: [{ file: filename, modality, effectivePack, packSource }],
|
|
548
1578
|
checkedCount: 1,
|
|
549
1579
|
skipped: [],
|
|
550
|
-
|
|
1580
|
+
coverageWarnings,
|
|
1581
|
+
findings: outFindings,
|
|
551
1582
|
unusedSuppressions: reportUnused ? res.unusedSuppressions : [],
|
|
552
|
-
...(includeProfile && (modality
|
|
1583
|
+
...(includeProfile && PROSE_ML_MODALITIES.has(modality)
|
|
553
1584
|
? {
|
|
554
1585
|
profiles: [
|
|
555
1586
|
{
|
|
556
1587
|
file: filename,
|
|
557
|
-
profile: analyzeTextProfile(stdinText, { modality }),
|
|
558
|
-
pocketModel: summarizePocketForProfile(
|
|
1588
|
+
profile: profileObj || analyzeTextProfile(stdinText, { modality, config: fileConfig }),
|
|
1589
|
+
pocketModel: summarizePocketForProfile(pocketSrc),
|
|
559
1590
|
},
|
|
560
1591
|
],
|
|
561
1592
|
}
|
|
562
1593
|
: {}),
|
|
563
1594
|
};
|
|
564
|
-
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
1595
|
+
const outReport = compactJson ? applyCompactReport(report) : report;
|
|
1596
|
+
const rendered = colorizeTextReport(formatReport(outReport, format, lang, { quiet, failOn }), useColor);
|
|
1597
|
+
if (rendered) console.log(rendered);
|
|
1598
|
+
if (useColor && !quiet && format === "text" && findings.length === 0 && (!reportUnused || res.unusedSuppressions.length === 0) && !includeMl && !includePatterns) {
|
|
1599
|
+
console.log(lang === "zh" ? " 提示: 可加 --deep 启用统计画像与内置隐蔽套话模型。" : " hint: run with --deep to enable rhythm telemetry and Pocket ML scoring.");
|
|
1600
|
+
}
|
|
568
1601
|
process.exitCode = triggered ? 1 : 0;
|
|
569
1602
|
return;
|
|
570
1603
|
}
|
|
@@ -582,7 +1615,7 @@ function runCheck(args, packs) {
|
|
|
582
1615
|
const targets = positional.length > 0 ? positional : changedMap ? Array.from(changedMap.keys()).filter((p) => fs.existsSync(path.join(cwd, p))) : ["."];
|
|
583
1616
|
let collected;
|
|
584
1617
|
try {
|
|
585
|
-
collected = collectFiles(targets, cwd, config);
|
|
1618
|
+
collected = collectFiles(targets, cwd, config, positional.length > 0);
|
|
586
1619
|
} catch (err) {
|
|
587
1620
|
console.error(`dislop: ${err.message}`);
|
|
588
1621
|
process.exit(2);
|
|
@@ -590,8 +1623,14 @@ function runCheck(args, packs) {
|
|
|
590
1623
|
|
|
591
1624
|
const allFindings = [];
|
|
592
1625
|
const allSkipped = [...collected.skipped];
|
|
1626
|
+
const allCoverageWarnings = [];
|
|
593
1627
|
const allUnused = [];
|
|
594
1628
|
const allProfiles = [];
|
|
1629
|
+
const fileMeta = [];
|
|
1630
|
+
const seenHashes = new Set();
|
|
1631
|
+
const seenPacks = new Set();
|
|
1632
|
+
const seenSources = new Set();
|
|
1633
|
+
const regPairs = [];
|
|
595
1634
|
let checkedCount = 0;
|
|
596
1635
|
let explicitUninspectable = collected.skipped.length > 0;
|
|
597
1636
|
|
|
@@ -599,22 +1638,31 @@ function runCheck(args, packs) {
|
|
|
599
1638
|
if (changedMap && !changedMap.has(item.rel)) continue;
|
|
600
1639
|
let res;
|
|
601
1640
|
try {
|
|
602
|
-
res = inspectSingleFile(item, packs, flags.pack || null, config, {
|
|
1641
|
+
res = inspectSingleFile(item, packs, flags.pack || null, config, {
|
|
1642
|
+
includeMl,
|
|
1643
|
+
includePatterns,
|
|
1644
|
+
includeProfile,
|
|
1645
|
+
banks,
|
|
1646
|
+
register: flagRegister,
|
|
1647
|
+
});
|
|
603
1648
|
} catch (err) {
|
|
604
1649
|
console.error(`dislop: ${err.message}`);
|
|
605
1650
|
process.exit(2);
|
|
606
1651
|
}
|
|
607
1652
|
if (res.checked) {
|
|
608
1653
|
checkedCount += 1;
|
|
609
|
-
if (
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
1654
|
+
if (res.register) regPairs.push({ register: res.register, registerSource: res.registerSource || "default" });
|
|
1655
|
+
if (res.effectivePack) seenPacks.add(res.effectivePack);
|
|
1656
|
+
if (res.packSource) seenSources.add(res.packSource);
|
|
1657
|
+
if (res.rulesetHash) seenHashes.add(res.rulesetHash);
|
|
1658
|
+
fileMeta.push({
|
|
1659
|
+
file: item.rel,
|
|
1660
|
+
modality: item.modality,
|
|
1661
|
+
effectivePack: res.effectivePack || null,
|
|
1662
|
+
packSource: res.packSource || null,
|
|
1663
|
+
});
|
|
1664
|
+
if (res.profileItem) {
|
|
1665
|
+
allProfiles.push(res.profileItem);
|
|
618
1666
|
}
|
|
619
1667
|
} else if (item.explicit) {
|
|
620
1668
|
explicitUninspectable = true;
|
|
@@ -623,35 +1671,67 @@ function runCheck(args, packs) {
|
|
|
623
1671
|
if (changedMap && changedMap.has(item.rel)) {
|
|
624
1672
|
const allowedLines = changedMap.get(item.rel);
|
|
625
1673
|
if (allowedLines instanceof Set) {
|
|
626
|
-
fileFindings = fileFindings.filter((f) =>
|
|
1674
|
+
fileFindings = fileFindings.filter((f) => {
|
|
1675
|
+
const startLine = Number.isInteger(f.line) ? f.line : 1;
|
|
1676
|
+
let endLine = Number.isInteger(f.endLine) && f.endLine >= startLine ? f.endLine : startLine;
|
|
1677
|
+
if (!Number.isInteger(f.endLine) && f.span && Number.isInteger(f.span.end) && res._cpLineStarts) {
|
|
1678
|
+
const endOff = Math.max(f.span.start || 0, f.span.end - 1);
|
|
1679
|
+
endLine = Math.max(startLine, cpOffsetToLine(res._cpLineStarts, endOff));
|
|
1680
|
+
}
|
|
1681
|
+
for (let ln = startLine; ln <= endLine; ln += 1) {
|
|
1682
|
+
if (allowedLines.has(ln)) return true;
|
|
1683
|
+
}
|
|
1684
|
+
return false;
|
|
1685
|
+
});
|
|
627
1686
|
}
|
|
628
1687
|
}
|
|
1688
|
+
if (ruleFilter) {
|
|
1689
|
+
fileFindings = fileFindings.filter((f) => ruleFilter.has(f.ruleId));
|
|
1690
|
+
}
|
|
629
1691
|
allFindings.push(...fileFindings);
|
|
630
1692
|
allSkipped.push(...res.skipped);
|
|
1693
|
+
if (res.coverageWarnings && res.coverageWarnings.length > 0) {
|
|
1694
|
+
allCoverageWarnings.push(...res.coverageWarnings);
|
|
1695
|
+
}
|
|
631
1696
|
if (reportUnused) {
|
|
632
1697
|
allUnused.push(...res.unusedSuppressions);
|
|
633
1698
|
}
|
|
634
1699
|
}
|
|
635
1700
|
|
|
1701
|
+
const shouldFail =
|
|
1702
|
+
allFindings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
|
|
1703
|
+
(reportUnused && allUnused.length > 0);
|
|
1704
|
+
const outFindings = quiet
|
|
1705
|
+
? allFindings.filter((f) => (SEVERITY_RANK[f.severity] || 1) >= SEVERITY_RANK[failOn])
|
|
1706
|
+
: allFindings;
|
|
1707
|
+
|
|
636
1708
|
const report = {
|
|
637
1709
|
version: ENGINE_VERSION,
|
|
1710
|
+
context: summarizeReportContext(regPairs, flagRegister),
|
|
1711
|
+
rulesetHash: seenHashes.size === 1 ? Array.from(seenHashes)[0] : seenHashes.size > 1 ? fnv1aHex(Array.from(seenHashes).sort().join("|")) : null,
|
|
1712
|
+
effectivePack: seenPacks.size === 1 ? Array.from(seenPacks)[0] : seenPacks.size > 1 ? "mixed" : flags.pack || null,
|
|
1713
|
+
packSource: seenSources.size === 1 ? Array.from(seenSources)[0] : seenSources.size > 1 ? "mixed" : null,
|
|
1714
|
+
changedFilter: Boolean(flags.changed || flags.staged),
|
|
1715
|
+
files: fileMeta,
|
|
638
1716
|
checkedCount,
|
|
639
1717
|
skipped: allSkipped,
|
|
640
|
-
|
|
1718
|
+
coverageWarnings: allCoverageWarnings,
|
|
1719
|
+
findings: outFindings,
|
|
641
1720
|
unusedSuppressions: allUnused,
|
|
642
1721
|
...(allProfiles.length > 0 ? { profiles: allProfiles } : {}),
|
|
643
1722
|
};
|
|
644
1723
|
|
|
645
|
-
const
|
|
1724
|
+
const outReport = compactJson ? applyCompactReport(report) : report;
|
|
1725
|
+
const rendered = colorizeTextReport(formatReport(outReport, format, lang, { quiet, failOn }), useColor);
|
|
646
1726
|
if (rendered) console.log(rendered);
|
|
1727
|
+
if (useColor && !quiet && format === "text" && allFindings.length === 0 && allUnused.length === 0 && !includeMl && !includePatterns && checkedCount > 0) {
|
|
1728
|
+
console.log(lang === "zh" ? " 提示: 可加 --deep 启用统计画像与内置隐蔽套话模型。" : " hint: run with --deep to enable rhythm telemetry and Pocket ML scoring.");
|
|
1729
|
+
}
|
|
647
1730
|
|
|
648
1731
|
if (explicitUninspectable || (checkedCount === 0 && allSkipped.length > 0)) {
|
|
649
1732
|
process.exitCode = 2;
|
|
650
1733
|
return;
|
|
651
1734
|
}
|
|
652
|
-
const shouldFail =
|
|
653
|
-
allFindings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
|
|
654
|
-
(reportUnused && allUnused.length > 0);
|
|
655
1735
|
process.exitCode = shouldFail ? 1 : 0;
|
|
656
1736
|
}
|
|
657
1737
|
|
|
@@ -681,7 +1761,11 @@ const POCKET_STEALTH_VAPOR_RULE = {
|
|
|
681
1761
|
};
|
|
682
1762
|
|
|
683
1763
|
function runExplain(args, packs, patternByRuleId) {
|
|
684
|
-
const { flags, positional } = parseFlags(args);
|
|
1764
|
+
const { flags, positional } = parseFlags(args, "explain");
|
|
1765
|
+
if (flags.help) {
|
|
1766
|
+
printSubcommandHelp("explain");
|
|
1767
|
+
return;
|
|
1768
|
+
}
|
|
685
1769
|
const format = flags.json ? "json" : flags.format || "text";
|
|
686
1770
|
assertTextOrJsonFormat(format);
|
|
687
1771
|
const ruleId = positional[0];
|
|
@@ -770,7 +1854,11 @@ function runExplain(args, packs, patternByRuleId) {
|
|
|
770
1854
|
}
|
|
771
1855
|
|
|
772
1856
|
function runPacks(args, packs) {
|
|
773
|
-
const { flags } = parseFlags(args);
|
|
1857
|
+
const { flags } = parseFlags(args, "packs");
|
|
1858
|
+
if (flags.help) {
|
|
1859
|
+
printSubcommandHelp("packs");
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
774
1862
|
const format = flags.json ? "json" : flags.format || "text";
|
|
775
1863
|
assertTextOrJsonFormat(format);
|
|
776
1864
|
const list = Object.values(packs).map((p) => ({
|
|
@@ -793,12 +1881,16 @@ function runPacks(args, packs) {
|
|
|
793
1881
|
}
|
|
794
1882
|
}
|
|
795
1883
|
|
|
796
|
-
const VALID_MODALITIES = new Set(["markdown", "text", "html", "css", "jsx", "svg", "docx", "pptx"]);
|
|
1884
|
+
const VALID_MODALITIES = new Set(["markdown", "text", "html", "css", "jsx", "svg", "docx", "pptx", "pdf", "image"]);
|
|
797
1885
|
const VALID_SEVERITIES = new Set(["error", "warning", "info"]);
|
|
798
1886
|
const VALID_TIERS = new Set(["invariant", "taste"]);
|
|
799
1887
|
|
|
800
1888
|
function runCatalog(args, packs, patternByRuleId) {
|
|
801
|
-
const { flags, positional } = parseFlags(args);
|
|
1889
|
+
const { flags, positional } = parseFlags(args, "catalog");
|
|
1890
|
+
if (flags.help) {
|
|
1891
|
+
printSubcommandHelp("catalog");
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
802
1894
|
const format = flags.json ? "json" : flags.format || "text";
|
|
803
1895
|
const lang = flags.lang || "en";
|
|
804
1896
|
if (!["text", "json", "md"].includes(format)) {
|
|
@@ -858,7 +1950,12 @@ function runCatalog(args, packs, patternByRuleId) {
|
|
|
858
1950
|
}
|
|
859
1951
|
}
|
|
860
1952
|
|
|
861
|
-
function runPackTest(packs) {
|
|
1953
|
+
function runPackTest(args, packs) {
|
|
1954
|
+
const { flags } = parseFlags(args, "pack-test");
|
|
1955
|
+
if (flags.help) {
|
|
1956
|
+
printSubcommandHelp("pack-test");
|
|
1957
|
+
return;
|
|
1958
|
+
}
|
|
862
1959
|
const errors = [];
|
|
863
1960
|
let assertions = 0;
|
|
864
1961
|
|
|
@@ -900,6 +1997,41 @@ function runPackTest(packs) {
|
|
|
900
1997
|
errors.push(`${pack.id}/${rule.id}: unbounded '.*' forbidden in portable pack regex: ${pat}`);
|
|
901
1998
|
}
|
|
902
1999
|
}
|
|
2000
|
+
// Validate registerOverrides + fixtures.register
|
|
2001
|
+
if (rule.registerOverrides) {
|
|
2002
|
+
if (rule.tier === "invariant") {
|
|
2003
|
+
errors.push(`${pack.id}/${rule.id}: invariant rules cannot define registerOverrides`);
|
|
2004
|
+
}
|
|
2005
|
+
const ovEntries = Object.entries(rule.registerOverrides);
|
|
2006
|
+
for (const [rk, rov] of ovEntries) {
|
|
2007
|
+
if (!VALID_REGISTERS.includes(rk) || rk === "unspecified") {
|
|
2008
|
+
errors.push(`${pack.id}/${rule.id}: invalid registerOverrides key '${rk}'`);
|
|
2009
|
+
}
|
|
2010
|
+
if (rov?.severity && SEVERITY_RANK[rov.severity] > SEVERITY_RANK[rule.severity]) {
|
|
2011
|
+
errors.push(`${pack.id}/${rule.id}: registerOverrides['${rk}'] cannot raise severity above '${rule.severity}'`);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
const regFixtures = rule.fixtures?.register || [];
|
|
2015
|
+
if (regFixtures.length === 0) {
|
|
2016
|
+
errors.push(`${pack.id}/${rule.id}: registerOverrides requires at least 1 fixtures.register assertion`);
|
|
2017
|
+
}
|
|
2018
|
+
for (const rf of regFixtures) {
|
|
2019
|
+
assertions += 1;
|
|
2020
|
+
const res = auditText(rf.text, {
|
|
2021
|
+
filename: `fixture.${sampleMod}`,
|
|
2022
|
+
modality: sampleMod,
|
|
2023
|
+
pack: effective,
|
|
2024
|
+
allowSyntheticFixtures: true,
|
|
2025
|
+
register: rf.register,
|
|
2026
|
+
});
|
|
2027
|
+
const hit = res.findings.find((f) => f.ruleId === rule.id);
|
|
2028
|
+
if (rf.expect === "skip") {
|
|
2029
|
+
if (hit) errors.push(`${pack.id}/${rule.id}: expected register '${rf.register}' to skip`);
|
|
2030
|
+
} else if (!hit || hit.severity !== rf.expect) {
|
|
2031
|
+
errors.push(`${pack.id}/${rule.id}: register '${rf.register}' expected '${rf.expect}', got '${hit?.severity || "none"}'`);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
903
2035
|
}
|
|
904
2036
|
}
|
|
905
2037
|
|
|
@@ -911,7 +2043,12 @@ function runPackTest(packs) {
|
|
|
911
2043
|
console.log(`dislop pack-test: ok (${Object.keys(packs).length} packs, ${assertions} fixture assertions passed)`);
|
|
912
2044
|
}
|
|
913
2045
|
|
|
914
|
-
function runInit() {
|
|
2046
|
+
function runInit(args = []) {
|
|
2047
|
+
const { flags } = parseFlags(args, "init");
|
|
2048
|
+
if (flags.help) {
|
|
2049
|
+
printSubcommandHelp("init");
|
|
2050
|
+
return;
|
|
2051
|
+
}
|
|
915
2052
|
const cwd = process.cwd();
|
|
916
2053
|
const cfgPath = path.join(cwd, ".dislop.json");
|
|
917
2054
|
if (!fs.existsSync(cfgPath)) {
|
|
@@ -936,6 +2073,9 @@ function runInit() {
|
|
|
936
2073
|
fs.writeFileSync(giPath, cur.replace(/\s*$/, "\n") + localEntry + "\n", "utf8");
|
|
937
2074
|
console.log(`Added ${localEntry} to .gitignore`);
|
|
938
2075
|
}
|
|
2076
|
+
} else if (fs.existsSync(path.join(cwd, ".git"))) {
|
|
2077
|
+
fs.writeFileSync(giPath, localEntry + "\n", "utf8");
|
|
2078
|
+
console.log(`Created .gitignore with ${localEntry}`);
|
|
939
2079
|
}
|
|
940
2080
|
}
|
|
941
2081
|
|
|
@@ -943,7 +2083,6 @@ function runInit() {
|
|
|
943
2083
|
|
|
944
2084
|
function runMcpServer(packs, patternByRuleId) {
|
|
945
2085
|
const cwd = process.cwd();
|
|
946
|
-
const config = loadConfig(cwd);
|
|
947
2086
|
const catalogEntries = buildCatalog(packs, patternByRuleId);
|
|
948
2087
|
const rl = readline.createInterface({ input: process.stdin, terminal: false });
|
|
949
2088
|
|
|
@@ -996,12 +2135,22 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
996
2135
|
if (!obj || typeof obj !== "object" || !cleanLang) return obj;
|
|
997
2136
|
return { [cleanLang]: obj[cleanLang] || obj.en || "" };
|
|
998
2137
|
};
|
|
2138
|
+
const localizeRevision = (rev) => {
|
|
2139
|
+
if (!rev || typeof rev !== "object") return null;
|
|
2140
|
+
if (!cleanLang) return rev;
|
|
2141
|
+
return {
|
|
2142
|
+
...rev,
|
|
2143
|
+
instruction: localizeObj(rev.instruction),
|
|
2144
|
+
avoid: localizeObj(rev.avoid),
|
|
2145
|
+
};
|
|
2146
|
+
};
|
|
999
2147
|
if (verbosity === "full") {
|
|
1000
2148
|
if (!cleanLang) return findings;
|
|
1001
2149
|
return findings.map((f) => ({
|
|
1002
2150
|
...f,
|
|
1003
2151
|
message: localizeObj(f.message),
|
|
1004
2152
|
deletionTest: localizeObj(f.deletionTest),
|
|
2153
|
+
revision: localizeRevision(f.revision),
|
|
1005
2154
|
}));
|
|
1006
2155
|
}
|
|
1007
2156
|
return findings.map((f) => ({
|
|
@@ -1009,6 +2158,8 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1009
2158
|
ruleId: f.ruleId,
|
|
1010
2159
|
tier: f.tier ?? "taste",
|
|
1011
2160
|
severity: f.severity,
|
|
2161
|
+
confidence: f.confidence || "medium",
|
|
2162
|
+
fixStrategy: f.fixStrategy || deriveFixStrategy({ id: f.ruleId, family: f.family }),
|
|
1012
2163
|
family: f.family ?? (f.dimension ? `${f.dimension}/${f.ruleId}` : null),
|
|
1013
2164
|
file: f.file,
|
|
1014
2165
|
modality: f.modality,
|
|
@@ -1018,6 +2169,7 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1018
2169
|
match: f.match,
|
|
1019
2170
|
message: localizeObj(f.message),
|
|
1020
2171
|
deletionTest: f.deletionTest ? localizeObj(f.deletionTest) : null,
|
|
2172
|
+
revision: localizeRevision(f.revision),
|
|
1021
2173
|
}));
|
|
1022
2174
|
}
|
|
1023
2175
|
|
|
@@ -1025,15 +2177,17 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1025
2177
|
{
|
|
1026
2178
|
name: "dislop_check",
|
|
1027
2179
|
description:
|
|
1028
|
-
"Check a draft (`text` or workspace-relative `path`) for AI-generation artifacts, clichés, and template slop across Markdown, HTML/CSS/JSX/SVG, Word (.docx),
|
|
2180
|
+
"Check a draft (`text` or workspace-relative `path`) for AI-generation artifacts, clichés, and template slop across Markdown, HTML/CSS/JSX/SVG, PNG/JPEG/WebP, Word (.docx), PowerPoint (.pptx), and PDF. Edit only the flagged spans using `fixStrategy`, then run `dislop_verify`.",
|
|
1029
2181
|
inputSchema: {
|
|
1030
2182
|
type: "object",
|
|
1031
2183
|
properties: {
|
|
1032
2184
|
text: { type: "string", description: "Draft text to inspect in memory" },
|
|
1033
|
-
path: { type: "string", description: "Workspace-relative file path (.md, .html, .css, .jsx, .svg, .docx, .pptx)" },
|
|
2185
|
+
path: { type: "string", description: "Workspace-relative file path (.md, .html, .css, .jsx, .svg, .png, .jpg, .jpeg, .webp, .docx, .pptx, .pdf)" },
|
|
1034
2186
|
pack: { type: "string", description: "Style pack ID (auto, business-brief, engineering-spec, regulated-comms, literary-essay, deck-and-ui, executive-deck)" },
|
|
2187
|
+
register: { type: "string", enum: ["auto", ...VALID_REGISTERS], description: "Optional writing register override (auto, unspecified, official, casual, argumentative, technical, marketing, narrative)" },
|
|
1035
2188
|
filename: { type: "string", description: "Virtual filename hint when inspecting `text`" },
|
|
1036
2189
|
profile: { type: "boolean", description: "Include 5-axis rhythm & concreteness telemetry on text/markdown (default true)" },
|
|
2190
|
+
deep: { type: "boolean", description: "Enable thorough inspection (Pocket ML + extended 6-dimension pattern bank)" },
|
|
1037
2191
|
ml: { type: "boolean", description: "Enable bundled 15 KB Pocket ML stealth-vapor paragraph detection (default false)" },
|
|
1038
2192
|
patterns: { type: "boolean", description: "Include extended 6-dimension pattern-bank probes (default false)" },
|
|
1039
2193
|
verbosity: { type: "string", enum: ["compact", "full"], description: "Default compact (omits per-hit exemplars to save context tokens; pass full to inline exemplars)" },
|
|
@@ -1042,31 +2196,33 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1042
2196
|
},
|
|
1043
2197
|
},
|
|
1044
2198
|
{
|
|
1045
|
-
name: "
|
|
2199
|
+
name: "dislop_verify",
|
|
1046
2200
|
description:
|
|
1047
|
-
"
|
|
2201
|
+
"Verify a revised draft against its original text (or Git baseline for workspace `path`): checks numbers/qualifiers, required `keep` terms, newly introduced AI slop, length bounds, and anti-degradation guardrails (author perspective, cadence, info density, modality).",
|
|
1048
2202
|
inputSchema: {
|
|
1049
2203
|
type: "object",
|
|
1050
2204
|
properties: {
|
|
1051
|
-
|
|
1052
|
-
|
|
2205
|
+
before: { type: "string", description: "Original text before revision (required unless `path` is provided)" },
|
|
2206
|
+
after: { type: "string", description: "Revised text after revision (required unless `path` is provided)" },
|
|
2207
|
+
path: { type: "string", description: "Workspace-relative file path to compare working tree against `gitRef`" },
|
|
2208
|
+
gitRef: { type: "string", description: "Git ref baseline when `path` is given (default HEAD)" },
|
|
2209
|
+
filename: { type: "string", description: "Optional virtual filename hint when passing `before`/`after`" },
|
|
2210
|
+
pack: { type: "string", description: "Optional pack ID or 'auto' to also verify findingsDelta" },
|
|
2211
|
+
register: { type: "string", enum: ["auto", ...VALID_REGISTERS], description: "Optional writing register override (auto, unspecified, official, casual, argumentative, technical, marketing, narrative)" },
|
|
2212
|
+
keep: { type: "array", items: { type: "string" }, description: "Protected terms/concepts that must stay intact in the revision" },
|
|
2213
|
+
allowAdded: { type: "boolean", description: "Allow new numbers not present in original (default false)" },
|
|
2214
|
+
strict: { type: "boolean", description: "Fail `ok` on any anti-degradation warning in addition to hard fact/error checks" },
|
|
1053
2215
|
},
|
|
1054
|
-
required: ["ruleId"],
|
|
1055
2216
|
},
|
|
1056
2217
|
},
|
|
1057
2218
|
{
|
|
1058
|
-
name: "
|
|
1059
|
-
description: "
|
|
1060
|
-
inputSchema: { type: "object", properties: {} },
|
|
1061
|
-
},
|
|
1062
|
-
{
|
|
1063
|
-
name: "dislop_catalog",
|
|
1064
|
-
description:
|
|
1065
|
-
"Search and browse dislop's 53-pattern AI-slop catalog by keyword, dimension, category, family, modality, severity, tier, or pack.",
|
|
2219
|
+
name: "dislop_rules",
|
|
2220
|
+
description: "Unified rule lookup: pass `ruleId` to explain a rule, filters (`query`/`pack`/`dimension`) to search, or empty object to list all packs.",
|
|
1066
2221
|
inputSchema: {
|
|
1067
2222
|
type: "object",
|
|
1068
2223
|
properties: {
|
|
1069
|
-
|
|
2224
|
+
ruleId: { type: "string", description: "Optional rule ID to explain with before/trap/after examples" },
|
|
2225
|
+
query: { type: "string", description: "Optional keyword search query" },
|
|
1070
2226
|
pack: { type: "string" },
|
|
1071
2227
|
category: { type: "string" },
|
|
1072
2228
|
dimension: { type: "string" },
|
|
@@ -1075,15 +2231,15 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1075
2231
|
severity: { type: "string", enum: ["error", "warning", "info"] },
|
|
1076
2232
|
tier: { type: "string", enum: ["invariant", "taste"] },
|
|
1077
2233
|
lang: { type: "string", enum: ["en", "zh"] },
|
|
1078
|
-
includeExemplars: { type: "boolean"
|
|
2234
|
+
includeExemplars: { type: "boolean" },
|
|
1079
2235
|
limit: { type: "integer", minimum: 1, maximum: 100 },
|
|
1080
2236
|
},
|
|
1081
2237
|
},
|
|
1082
2238
|
},
|
|
1083
2239
|
{
|
|
1084
|
-
name: "
|
|
2240
|
+
name: "dislop_voice_extract",
|
|
1085
2241
|
description:
|
|
1086
|
-
"Extract a deterministic offline `dislop.voice/1`
|
|
2242
|
+
"Extract a deterministic offline `dislop.voice/1` personal style card from 1-15 clean author samples (0 network calls, 0 uploads).",
|
|
1087
2243
|
inputSchema: {
|
|
1088
2244
|
type: "object",
|
|
1089
2245
|
properties: {
|
|
@@ -1132,8 +2288,26 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1132
2288
|
} catch {
|
|
1133
2289
|
return;
|
|
1134
2290
|
}
|
|
1135
|
-
|
|
2291
|
+
if (!req || typeof req !== "object" || Array.isArray(req)) {
|
|
2292
|
+
send({
|
|
2293
|
+
jsonrpc: "2.0",
|
|
2294
|
+
id: null,
|
|
2295
|
+
error: { code: -32600, message: "Invalid Request: expected JSON-RPC object" },
|
|
2296
|
+
});
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
const { id, method } = req;
|
|
1136
2300
|
if (id === undefined || id === null) return;
|
|
2301
|
+
const rawParams = req.params;
|
|
2302
|
+
if (rawParams !== undefined && (!rawParams || typeof rawParams !== "object" || Array.isArray(rawParams))) {
|
|
2303
|
+
send({
|
|
2304
|
+
jsonrpc: "2.0",
|
|
2305
|
+
id,
|
|
2306
|
+
error: { code: -32600, message: "Invalid Request: params must be an object" },
|
|
2307
|
+
});
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
const params = rawParams || {};
|
|
1137
2311
|
|
|
1138
2312
|
if (method === "initialize") {
|
|
1139
2313
|
const clientVersion = params.protocolVersion || "2024-11-05";
|
|
@@ -1161,8 +2335,170 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1161
2335
|
|
|
1162
2336
|
if (method === "tools/call") {
|
|
1163
2337
|
const name = params.name;
|
|
1164
|
-
const
|
|
2338
|
+
const rawArgs = params.arguments;
|
|
2339
|
+
if (rawArgs !== undefined && (!rawArgs || typeof rawArgs !== "object" || Array.isArray(rawArgs))) {
|
|
2340
|
+
send({
|
|
2341
|
+
jsonrpc: "2.0",
|
|
2342
|
+
id,
|
|
2343
|
+
error: { code: -32602, message: "Invalid params: arguments must be an object" },
|
|
2344
|
+
});
|
|
2345
|
+
return;
|
|
2346
|
+
}
|
|
2347
|
+
const args = rawArgs || {};
|
|
1165
2348
|
try {
|
|
2349
|
+
const resolveWorkspaceFileMcp = (relOrAbsPath) => {
|
|
2350
|
+
const realCwd = fs.realpathSync(cwd);
|
|
2351
|
+
const resolved = path.resolve(cwd, relOrAbsPath);
|
|
2352
|
+
if (!fs.existsSync(resolved)) {
|
|
2353
|
+
const lexReal = path.relative(realCwd, path.resolve(realCwd, relOrAbsPath));
|
|
2354
|
+
const lexCwd = path.relative(path.resolve(cwd), resolved);
|
|
2355
|
+
const escapesBoth =
|
|
2356
|
+
(lexReal === ".." || lexReal.startsWith(`..${path.sep}`) || path.isAbsolute(lexReal)) &&
|
|
2357
|
+
(lexCwd === ".." || lexCwd.startsWith(`..${path.sep}`) || path.isAbsolute(lexCwd));
|
|
2358
|
+
return {
|
|
2359
|
+
error: escapesBoth
|
|
2360
|
+
? "Path must stay within the current workspace directory."
|
|
2361
|
+
: `File not found: ${relOrAbsPath}`,
|
|
2362
|
+
};
|
|
2363
|
+
}
|
|
2364
|
+
if (!fs.statSync(resolved).isFile()) {
|
|
2365
|
+
return { error: `File not found: ${relOrAbsPath}` };
|
|
2366
|
+
}
|
|
2367
|
+
const realTarget = fs.realpathSync(resolved);
|
|
2368
|
+
const rel = path.relative(realCwd, realTarget);
|
|
2369
|
+
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
2370
|
+
return { error: "Path must stay within the current workspace directory." };
|
|
2371
|
+
}
|
|
2372
|
+
return { realTarget, posixRel: rel.split(path.sep).join("/") };
|
|
2373
|
+
};
|
|
2374
|
+
|
|
2375
|
+
const resolveExplainById = (ruleId, langArg) => {
|
|
2376
|
+
for (const p of Object.values(packs)) {
|
|
2377
|
+
const rule = (p.rules || []).find((r) => r.id === ruleId);
|
|
2378
|
+
if (rule) return formatRuleForExplain(rule, p.id, langArg);
|
|
2379
|
+
}
|
|
2380
|
+
const pat = patternByRuleId && patternByRuleId[ruleId];
|
|
2381
|
+
if (pat) {
|
|
2382
|
+
const guards = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
|
|
2383
|
+
const synthRule = {
|
|
2384
|
+
id: ruleId,
|
|
2385
|
+
tier: "taste",
|
|
2386
|
+
severity: pat.severityDefault || "info",
|
|
2387
|
+
category: pat.category || "general",
|
|
2388
|
+
family: pat.dimension ? `${pat.dimension}/${ruleId}` : "pattern-bank",
|
|
2389
|
+
modalities: pat.modalities || ["markdown", "text"],
|
|
2390
|
+
tags: pat.tags || [],
|
|
2391
|
+
message: pat.mechanism || pat.name || { en: "", zh: "" },
|
|
2392
|
+
...(guards ? { deletionTest: { en: guards, zh: guards } } : {}),
|
|
2393
|
+
...(pat.exemplar ? { exemplar: pat.exemplar } : {}),
|
|
2394
|
+
};
|
|
2395
|
+
return formatRuleForExplain(synthRule, pat.packId || "pattern-bank", langArg);
|
|
2396
|
+
}
|
|
2397
|
+
if (ruleId === "pocket-stealth-vapor") {
|
|
2398
|
+
return formatRuleForExplain(POCKET_STEALTH_VAPOR_RULE, "pocket-model", langArg);
|
|
2399
|
+
}
|
|
2400
|
+
return null;
|
|
2401
|
+
};
|
|
2402
|
+
|
|
2403
|
+
if (name === "dislop_rules") {
|
|
2404
|
+
if (args.ruleId) {
|
|
2405
|
+
const explained = resolveExplainById(args.ruleId, args.lang);
|
|
2406
|
+
if (explained) toolResult(id, explained);
|
|
2407
|
+
else toolResult(id, { error: `Unknown ruleId '${args.ruleId}'` }, true);
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
const hasFilter = Boolean(
|
|
2411
|
+
args.query || args.pack || args.category || args.dimension || args.family || args.modality || args.severity || args.tier
|
|
2412
|
+
);
|
|
2413
|
+
if (hasFilter) {
|
|
2414
|
+
const result = queryCatalog(catalogEntries, {
|
|
2415
|
+
query: args.query || "",
|
|
2416
|
+
pack: args.pack || null,
|
|
2417
|
+
category: args.category || null,
|
|
2418
|
+
dimension: args.dimension || null,
|
|
2419
|
+
family: args.family || null,
|
|
2420
|
+
modality: args.modality || null,
|
|
2421
|
+
severity: args.severity || null,
|
|
2422
|
+
tier: args.tier || null,
|
|
2423
|
+
includeExemplars: args.includeExemplars !== false,
|
|
2424
|
+
limit: Number.isInteger(args.limit) && args.limit > 0 ? args.limit : null,
|
|
2425
|
+
});
|
|
2426
|
+
toolResult(id, result);
|
|
2427
|
+
return;
|
|
2428
|
+
}
|
|
2429
|
+
const list = Object.values(packs).map((p) => ({
|
|
2430
|
+
id: p.id,
|
|
2431
|
+
tier: p.tier,
|
|
2432
|
+
name: p.name,
|
|
2433
|
+
modalities: p.modalities,
|
|
2434
|
+
ruleCount: (p.rules || []).length,
|
|
2435
|
+
summary: p.summary,
|
|
2436
|
+
}));
|
|
2437
|
+
toolResult(id, { packs: list });
|
|
2438
|
+
return;
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
if (name === "dislop_verify") {
|
|
2442
|
+
const liveConfig = loadConfig(cwd);
|
|
2443
|
+
const hasBefore = typeof args.before === "string";
|
|
2444
|
+
const hasAfter = typeof args.after === "string";
|
|
2445
|
+
const hasPath = typeof args.path === "string" && args.path.trim().length > 0;
|
|
2446
|
+
let beforeText;
|
|
2447
|
+
let afterText;
|
|
2448
|
+
let fn = args.filename || "draft.md";
|
|
2449
|
+
if (hasPath) {
|
|
2450
|
+
const ws = resolveWorkspaceFileMcp(args.path);
|
|
2451
|
+
if (ws.error) {
|
|
2452
|
+
toolResult(id, { error: ws.error }, true);
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
fn = ws.posixRel;
|
|
2456
|
+
afterText = decodeUtf8Strict(fs.readFileSync(ws.realTarget));
|
|
2457
|
+
beforeText = readGitBaselineForFile(ws.realTarget, typeof args.gitRef === "string" && args.gitRef.trim() ? args.gitRef.trim() : "HEAD");
|
|
2458
|
+
} else if (hasBefore && hasAfter) {
|
|
2459
|
+
beforeText = args.before;
|
|
2460
|
+
afterText = args.after;
|
|
2461
|
+
} else {
|
|
2462
|
+
toolResult(id, { error: "Provide both `before` and `after` strings, or a workspace `path`." }, true);
|
|
2463
|
+
return;
|
|
2464
|
+
}
|
|
2465
|
+
const mod = detectModality(fn) || "markdown";
|
|
2466
|
+
const fileCfg = resolveConfigForFile(fn, liveConfig);
|
|
2467
|
+
let argRegister = null;
|
|
2468
|
+
if (args.register !== undefined) {
|
|
2469
|
+
if (typeof args.register !== "string") {
|
|
2470
|
+
toolResult(id, { error: `Invalid register (expected string: auto, ${VALID_REGISTERS.join(", ")})` }, true);
|
|
2471
|
+
return;
|
|
2472
|
+
}
|
|
2473
|
+
const normReg = args.register.trim().toLowerCase();
|
|
2474
|
+
if (!normReg || (normReg !== "auto" && !VALID_REGISTERS.includes(normReg))) {
|
|
2475
|
+
toolResult(id, { error: `Invalid register '${args.register}' (expected auto, ${VALID_REGISTERS.join(", ")})` }, true);
|
|
2476
|
+
return;
|
|
2477
|
+
}
|
|
2478
|
+
argRegister = normReg;
|
|
2479
|
+
}
|
|
2480
|
+
const packRes = resolveTextPackAndSource(afterText, fn, mod, args.pack || "auto", fileCfg, packs);
|
|
2481
|
+
const keepTerms = Array.isArray(args.keep)
|
|
2482
|
+
? args.keep
|
|
2483
|
+
: typeof args.keep === "string"
|
|
2484
|
+
? args.keep.split(",").map((x) => x.trim()).filter(Boolean)
|
|
2485
|
+
: [];
|
|
2486
|
+
const out = verifyRevisionBundle(beforeText, afterText, {
|
|
2487
|
+
filename: fn,
|
|
2488
|
+
modality: mod,
|
|
2489
|
+
pack: packRes.pack,
|
|
2490
|
+
config: fileCfg,
|
|
2491
|
+
register: argRegister,
|
|
2492
|
+
keepTerms,
|
|
2493
|
+
allowAdded: Boolean(args.allowAdded),
|
|
2494
|
+
strict: Boolean(args.strict),
|
|
2495
|
+
});
|
|
2496
|
+
out.effectivePack = packRes.effectivePack;
|
|
2497
|
+
out.packSource = packRes.packSource;
|
|
2498
|
+
toolResult(id, out);
|
|
2499
|
+
return;
|
|
2500
|
+
}
|
|
2501
|
+
|
|
1166
2502
|
if (name === "dislop_packs") {
|
|
1167
2503
|
const list = Object.values(packs).map((p) => ({
|
|
1168
2504
|
id: p.id,
|
|
@@ -1245,60 +2581,107 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1245
2581
|
|
|
1246
2582
|
const liveConfig = loadConfig(cwd);
|
|
1247
2583
|
const verbosity = args.verbosity === "full" ? "full" : "compact";
|
|
1248
|
-
const includeMl = Boolean(args.ml);
|
|
1249
|
-
const includePatterns = Boolean(args.patterns);
|
|
2584
|
+
const includeMl = Boolean(args.ml || args.deep);
|
|
2585
|
+
const includePatterns = Boolean(args.patterns || args.deep);
|
|
1250
2586
|
const wantProfile = args.profile !== false;
|
|
1251
2587
|
const banks = includePatterns ? loadPatternBanks() : null;
|
|
2588
|
+
let argRegister = null;
|
|
2589
|
+
if (args.register !== undefined && args.register !== null) {
|
|
2590
|
+
if (typeof args.register !== "string") {
|
|
2591
|
+
toolResult(
|
|
2592
|
+
id,
|
|
2593
|
+
{ error: `Invalid register (expected string: auto, ${VALID_REGISTERS.join(", ")})` },
|
|
2594
|
+
true
|
|
2595
|
+
);
|
|
2596
|
+
return;
|
|
2597
|
+
}
|
|
2598
|
+
const rawReg = args.register;
|
|
2599
|
+
const normReg = rawReg.trim().toLowerCase();
|
|
2600
|
+
if (!normReg || (normReg !== "auto" && !VALID_REGISTERS.includes(normReg))) {
|
|
2601
|
+
toolResult(
|
|
2602
|
+
id,
|
|
2603
|
+
{ error: `Invalid register '${rawReg}' (expected auto, ${VALID_REGISTERS.join(", ")})` },
|
|
2604
|
+
true
|
|
2605
|
+
);
|
|
2606
|
+
return;
|
|
2607
|
+
}
|
|
2608
|
+
argRegister = normReg;
|
|
2609
|
+
}
|
|
1252
2610
|
|
|
1253
2611
|
if (hasText) {
|
|
1254
2612
|
const fn = args.filename || "draft.md";
|
|
1255
2613
|
const mod = detectModality(fn) || "markdown";
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
? null
|
|
1261
|
-
: args.pack || null;
|
|
1262
|
-
const packId = pickPackForFile(fn, mod, effPack, liveConfig);
|
|
1263
|
-
const pack = resolveEffectivePack(packId, packs, liveConfig);
|
|
1264
|
-
const res = auditText(args.text, { filename: fn, modality: mod, pack, config: liveConfig });
|
|
2614
|
+
const fileCfg = resolveConfigForFile(fn, liveConfig);
|
|
2615
|
+
const { pack, effectivePack, packSource } = resolveTextPackAndSource(args.text, fn, mod, args.pack || null, fileCfg, packs);
|
|
2616
|
+
const regInfo = resolveRegister(args.text, { filename: fn, flagRegister: argRegister, config: fileCfg });
|
|
2617
|
+
const res = auditText(args.text, { filename: fn, modality: mod, pack, config: fileCfg, register: argRegister });
|
|
1265
2618
|
let findings = res.findings;
|
|
1266
2619
|
if (includePatterns) {
|
|
1267
|
-
findings = mergePatternBankFindings(
|
|
2620
|
+
findings = mergePatternBankFindings(
|
|
2621
|
+
findings,
|
|
2622
|
+
auditPatterns(args.text, { filename: fn, modality: mod, banks, config: fileCfg }).findings,
|
|
2623
|
+
{ packs, pack, register: regInfo.register, config: fileCfg }
|
|
2624
|
+
);
|
|
1268
2625
|
}
|
|
1269
|
-
|
|
1270
|
-
|
|
2626
|
+
const needsCoverageProfile = codePointLength(args.text) >= 2000 || mod === "html";
|
|
2627
|
+
const profile = PROSE_ML_MODALITIES.has(mod) && (wantProfile || includeMl || needsCoverageProfile)
|
|
2628
|
+
? analyzeTextProfile(args.text, { modality: mod, config: fileCfg })
|
|
2629
|
+
: null;
|
|
2630
|
+
if (includeMl && PROSE_ML_MODALITIES.has(mod)) {
|
|
2631
|
+
const mlSrc = mod === "html" || mod === "svg" ? buildZones(args.text, mod, fileCfg).prose : args.text;
|
|
2632
|
+
findings = [
|
|
2633
|
+
...findings,
|
|
2634
|
+
...buildPocketMlFindings(mlSrc, fn, findings, null, {
|
|
2635
|
+
profile,
|
|
2636
|
+
modality: mod,
|
|
2637
|
+
register: regInfo.register,
|
|
2638
|
+
}).findings,
|
|
2639
|
+
];
|
|
1271
2640
|
}
|
|
1272
|
-
const profile = wantProfile && (mod === "markdown" || mod === "text") ? analyzeTextProfile(args.text, { modality: mod }) : null;
|
|
1273
2641
|
const formatted = formatFindingsForMcp(findings, verbosity, args.lang);
|
|
1274
2642
|
toolResult(id, {
|
|
1275
|
-
pack:
|
|
2643
|
+
pack: effectivePack,
|
|
2644
|
+
packSource,
|
|
2645
|
+
rulesetHash: computeRulesetHash(pack),
|
|
1276
2646
|
modality: mod,
|
|
2647
|
+
context: { register: regInfo.register, registerSource: regInfo.registerSource },
|
|
1277
2648
|
checked: true,
|
|
1278
2649
|
skipped: [],
|
|
2650
|
+
coverageWarnings: collectTextCoverageWarnings(args.text, mod, fn, profile),
|
|
1279
2651
|
count: formatted.length,
|
|
1280
2652
|
findings: formatted,
|
|
1281
2653
|
...(verbosity === "compact" && formatted.length > 0
|
|
1282
2654
|
? { explainHint: "Call dislop_explain(ruleId) for before/trap/after examples." }
|
|
1283
2655
|
: {}),
|
|
1284
|
-
...(profile ? { profile } : {}),
|
|
2656
|
+
...(wantProfile && profile ? { profile } : {}),
|
|
1285
2657
|
});
|
|
1286
2658
|
return;
|
|
1287
2659
|
}
|
|
1288
2660
|
|
|
1289
|
-
// Check lexical workspace containment BEFORE touching filesystem, then realpath containment against symlinks
|
|
1290
2661
|
const realCwd = fs.realpathSync(cwd);
|
|
1291
|
-
const
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
2662
|
+
const resolved = path.resolve(cwd, args.path);
|
|
2663
|
+
if (!fs.existsSync(resolved)) {
|
|
2664
|
+
const lexReal = path.relative(realCwd, path.resolve(realCwd, args.path));
|
|
2665
|
+
const lexCwd = path.relative(path.resolve(cwd), resolved);
|
|
2666
|
+
const escapesBoth =
|
|
2667
|
+
(lexReal === ".." || lexReal.startsWith(`..${path.sep}`) || path.isAbsolute(lexReal)) &&
|
|
2668
|
+
(lexCwd === ".." || lexCwd.startsWith(`..${path.sep}`) || path.isAbsolute(lexCwd));
|
|
2669
|
+
toolResult(
|
|
2670
|
+
id,
|
|
2671
|
+
{
|
|
2672
|
+
error: escapesBoth
|
|
2673
|
+
? "Path must stay within the current workspace directory."
|
|
2674
|
+
: `File not found: ${args.path}`,
|
|
2675
|
+
},
|
|
2676
|
+
true
|
|
2677
|
+
);
|
|
1295
2678
|
return;
|
|
1296
2679
|
}
|
|
1297
|
-
if (!fs.
|
|
2680
|
+
if (!fs.statSync(resolved).isFile()) {
|
|
1298
2681
|
toolResult(id, { error: `File not found: ${args.path}` }, true);
|
|
1299
2682
|
return;
|
|
1300
2683
|
}
|
|
1301
|
-
const realTarget = fs.realpathSync(
|
|
2684
|
+
const realTarget = fs.realpathSync(resolved);
|
|
1302
2685
|
const rel = path.relative(realCwd, realTarget);
|
|
1303
2686
|
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
1304
2687
|
toolResult(id, { error: "Path must stay within the current workspace directory." }, true);
|
|
@@ -1310,35 +2693,24 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1310
2693
|
return;
|
|
1311
2694
|
}
|
|
1312
2695
|
const posixRel = rel.split(path.sep).join("/");
|
|
1313
|
-
let rawTxtForPack = null;
|
|
1314
|
-
if ((mod === "markdown" || mod === "text") && (args.pack === "auto" || wantProfile)) {
|
|
1315
|
-
try {
|
|
1316
|
-
rawTxtForPack = decodeUtf8Strict(fs.readFileSync(realTarget));
|
|
1317
|
-
} catch {}
|
|
1318
|
-
}
|
|
1319
|
-
const effPackArg =
|
|
1320
|
-
args.pack === "auto" && rawTxtForPack !== null && (mod === "markdown" || mod === "text")
|
|
1321
|
-
? predictPackWithPocketRouter(rawTxtForPack).recommendedPack
|
|
1322
|
-
: args.pack === "auto"
|
|
1323
|
-
? null
|
|
1324
|
-
: args.pack || null;
|
|
1325
2696
|
const res = inspectSingleFile(
|
|
1326
2697
|
{ absPath: realTarget, rel: posixRel, modality: mod },
|
|
1327
2698
|
packs,
|
|
1328
|
-
|
|
2699
|
+
args.pack || null,
|
|
1329
2700
|
liveConfig,
|
|
1330
|
-
{ includeMl, includePatterns, banks }
|
|
2701
|
+
{ includeMl, includePatterns, includeProfile: wantProfile, banks, register: argRegister }
|
|
1331
2702
|
);
|
|
1332
|
-
|
|
1333
|
-
if (res.checked && wantProfile && rawTxtForPack !== null && (mod === "markdown" || mod === "text")) {
|
|
1334
|
-
profile = analyzeTextProfile(rawTxtForPack, { modality: mod });
|
|
1335
|
-
}
|
|
2703
|
+
const profile = res.profileItem ? res.profileItem.profile : null;
|
|
1336
2704
|
const formatted = formatFindingsForMcp(res.findings, verbosity, args.lang);
|
|
1337
2705
|
toolResult(id, {
|
|
1338
|
-
pack: pickPackForFile(posixRel, mod,
|
|
2706
|
+
pack: res.effectivePack || pickPackForFile(posixRel, mod, args.pack || null, liveConfig),
|
|
2707
|
+
packSource: res.packSource || null,
|
|
2708
|
+
rulesetHash: res.rulesetHash || null,
|
|
1339
2709
|
modality: mod,
|
|
2710
|
+
context: { register: res.register || "unspecified", registerSource: res.registerSource || "default" },
|
|
1340
2711
|
checked: res.checked,
|
|
1341
2712
|
skipped: res.skipped,
|
|
2713
|
+
coverageWarnings: res.coverageWarnings || [],
|
|
1342
2714
|
count: formatted.length,
|
|
1343
2715
|
findings: formatted,
|
|
1344
2716
|
...(verbosity === "compact" && formatted.length > 0
|
|
@@ -1349,7 +2721,7 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1349
2721
|
return;
|
|
1350
2722
|
}
|
|
1351
2723
|
|
|
1352
|
-
if (name === "dislop_voice_extract_offline") {
|
|
2724
|
+
if (name === "dislop_voice_extract_offline" || name === "dislop_voice_extract") {
|
|
1353
2725
|
if (!Array.isArray(args.samples) || args.samples.length === 0) {
|
|
1354
2726
|
toolResult(id, { error: "Non-empty `samples` string array is required." }, true);
|
|
1355
2727
|
return;
|
|
@@ -1413,7 +2785,11 @@ function runMcpServer(packs, patternByRuleId) {
|
|
|
1413
2785
|
}
|
|
1414
2786
|
|
|
1415
2787
|
function runResources(rest, packs) {
|
|
1416
|
-
const { flags } = parseFlags(rest);
|
|
2788
|
+
const { flags } = parseFlags(rest, "resources");
|
|
2789
|
+
if (flags.help) {
|
|
2790
|
+
printSubcommandHelp("resources");
|
|
2791
|
+
return;
|
|
2792
|
+
}
|
|
1417
2793
|
const format = flags.json ? "json" : flags.format || "text";
|
|
1418
2794
|
assertTextOrJsonFormat(format);
|
|
1419
2795
|
const asJson = format === "json";
|
|
@@ -1426,6 +2802,8 @@ function runResources(rest, packs) {
|
|
|
1426
2802
|
llmsIndex: "https://dislop.com/llms.txt",
|
|
1427
2803
|
catalog: "https://dislop.com/catalog.json",
|
|
1428
2804
|
awesomeIndex: "https://dislop.com/awesome/index.json",
|
|
2805
|
+
mcpServerCard: "https://dislop.com/.well-known/mcp/server-card.json",
|
|
2806
|
+
agentSkillsIndex: "https://dislop.com/.well-known/agent-skills/index.json",
|
|
1429
2807
|
tasks: [
|
|
1430
2808
|
"https://dislop.com/tasks/business-doc.md",
|
|
1431
2809
|
"https://dislop.com/tasks/web-and-deck.md",
|
|
@@ -1436,8 +2814,21 @@ function runResources(rest, packs) {
|
|
|
1436
2814
|
},
|
|
1437
2815
|
optionalCloudMcp: {
|
|
1438
2816
|
url: "https://dislop.com/mcp",
|
|
2817
|
+
oauthMetadata: "https://dislop.com/.well-known/oauth-protected-resource/mcp",
|
|
1439
2818
|
pricingAndFreeToken: "https://dislop.com/#pricing",
|
|
1440
|
-
|
|
2819
|
+
freeToolsNoLogin: ["dislop_check", "dislop_verify", "dislop_rules"],
|
|
2820
|
+
tools: [
|
|
2821
|
+
"dislop_check",
|
|
2822
|
+
"dislop_verify",
|
|
2823
|
+
"dislop_rules",
|
|
2824
|
+
"dislop_review",
|
|
2825
|
+
"dislop_deslop",
|
|
2826
|
+
"dislop_office",
|
|
2827
|
+
"dislop_visual_review",
|
|
2828
|
+
"dislop_voice_extract",
|
|
2829
|
+
"dislop_voice_manage",
|
|
2830
|
+
"dislop_account",
|
|
2831
|
+
],
|
|
1441
2832
|
},
|
|
1442
2833
|
};
|
|
1443
2834
|
if (asJson) {
|
|
@@ -1449,9 +2840,11 @@ function runResources(rest, packs) {
|
|
|
1449
2840
|
console.log(`\nFree read-only static resources (dislop.com):`);
|
|
1450
2841
|
console.log(` - Agent index : ${payload.staticResources.llmsIndex}`);
|
|
1451
2842
|
console.log(` - Full catalog: ${payload.staticResources.catalog}`);
|
|
1452
|
-
console.log(` - Awesome
|
|
2843
|
+
console.log(` - Awesome 90 : ${payload.staticResources.awesomeIndex}`);
|
|
2844
|
+
console.log(` - MCP card : ${payload.staticResources.mcpServerCard}`);
|
|
2845
|
+
console.log(` - Skills index: ${payload.staticResources.agentSkillsIndex}`);
|
|
1453
2846
|
console.log(` - Rule card : ${payload.staticResources.ruleTemplate}`);
|
|
1454
|
-
console.log(`\nOptional hosted Cloud Remote MCP (login
|
|
2847
|
+
console.log(`\nOptional hosted Cloud Remote MCP (0-credit check/verify/rules need no login; 30 free credits/mo after sign-in):`);
|
|
1455
2848
|
console.log(` - Endpoint : ${payload.optionalCloudMcp.url}`);
|
|
1456
2849
|
console.log(` - Free token : ${payload.optionalCloudMcp.pricingAndFreeToken}`);
|
|
1457
2850
|
}
|
|
@@ -1469,7 +2862,11 @@ function loadPatternBanks(customPatternsDir = PATTERNS_DIR) {
|
|
|
1469
2862
|
}
|
|
1470
2863
|
|
|
1471
2864
|
function runPatterns(args) {
|
|
1472
|
-
const { flags, positional } = parseFlags(args);
|
|
2865
|
+
const { flags, positional } = parseFlags(args, "patterns");
|
|
2866
|
+
if (flags.help) {
|
|
2867
|
+
printSubcommandHelp("patterns");
|
|
2868
|
+
return;
|
|
2869
|
+
}
|
|
1473
2870
|
const format = flags.json ? "json" : flags.format || "text";
|
|
1474
2871
|
assertTextOrJsonFormat(format);
|
|
1475
2872
|
const lang = flags.lang || "en";
|
|
@@ -1496,6 +2893,10 @@ function runPatterns(args) {
|
|
|
1496
2893
|
process.exit(2);
|
|
1497
2894
|
}
|
|
1498
2895
|
modality = detected;
|
|
2896
|
+
if (modality === "pdf" || modality === "image") {
|
|
2897
|
+
console.error(`dislop: unsupported modality '${modality}' for patterns (use 'dislop check' for PDF and image files)`);
|
|
2898
|
+
process.exit(2);
|
|
2899
|
+
}
|
|
1499
2900
|
const buf = fs.readFileSync(abs);
|
|
1500
2901
|
try {
|
|
1501
2902
|
if (modality === "pptx" || modality === "docx") {
|
|
@@ -1528,7 +2929,11 @@ function runPatterns(args) {
|
|
|
1528
2929
|
}
|
|
1529
2930
|
|
|
1530
2931
|
function runVoice(args) {
|
|
1531
|
-
const { flags, positional } = parseFlags(args);
|
|
2932
|
+
const { flags, positional } = parseFlags(args, "voice");
|
|
2933
|
+
if (flags.help) {
|
|
2934
|
+
printSubcommandHelp("voice");
|
|
2935
|
+
return;
|
|
2936
|
+
}
|
|
1532
2937
|
const format = flags.json ? "json" : flags.format || "text";
|
|
1533
2938
|
assertTextOrJsonFormat(format);
|
|
1534
2939
|
const lang = flags.lang || "auto";
|
|
@@ -1603,6 +3008,17 @@ async function runLocalDeslopCli(target, flags, packs) {
|
|
|
1603
3008
|
}
|
|
1604
3009
|
const modality = detectModality(filename) || "markdown";
|
|
1605
3010
|
const config = loadConfig(process.cwd(), flags.config || null);
|
|
3011
|
+
let flagRegister = null;
|
|
3012
|
+
if (flags.register !== undefined) {
|
|
3013
|
+
const norm = String(flags.register).trim().toLowerCase();
|
|
3014
|
+
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
3015
|
+
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
3016
|
+
process.exit(2);
|
|
3017
|
+
}
|
|
3018
|
+
flagRegister = norm;
|
|
3019
|
+
}
|
|
3020
|
+
const fileCfg = resolveConfigForFile(filename, config);
|
|
3021
|
+
const regInfo = resolveRegister(rawText, { filename, flagRegister, config: fileCfg });
|
|
1606
3022
|
const explicitPack =
|
|
1607
3023
|
flags.pack === "auto"
|
|
1608
3024
|
? predictPackWithPocketRouter(rawText).recommendedPack
|
|
@@ -1616,6 +3032,7 @@ async function runLocalDeslopCli(target, flags, packs) {
|
|
|
1616
3032
|
text: rawText,
|
|
1617
3033
|
pack,
|
|
1618
3034
|
modality,
|
|
3035
|
+
register: regInfo.register,
|
|
1619
3036
|
endpoint: flags.endpoint || null,
|
|
1620
3037
|
model: flags.model || null,
|
|
1621
3038
|
allowLan: Boolean(flags["allow-lan"]),
|
|
@@ -1658,8 +3075,12 @@ async function runLocalDeslopCli(target, flags, packs) {
|
|
|
1658
3075
|
}
|
|
1659
3076
|
}
|
|
1660
3077
|
|
|
1661
|
-
async function runModel(args, packs) {
|
|
1662
|
-
const { flags, positional } = parseFlags(args);
|
|
3078
|
+
async function runModel(args, packs, cmdAlias = "model") {
|
|
3079
|
+
const { flags, positional } = parseFlags(args, cmdAlias);
|
|
3080
|
+
if (flags.help) {
|
|
3081
|
+
printSubcommandHelp(cmdAlias);
|
|
3082
|
+
return;
|
|
3083
|
+
}
|
|
1663
3084
|
const action = positional[0] || "status";
|
|
1664
3085
|
const validActions = new Set(["status", "recommend", "score", "install", "setup", "import", "remove", "rm", "deslop"]);
|
|
1665
3086
|
if (!validActions.has(action)) {
|
|
@@ -1897,55 +3318,1208 @@ async function runModel(args, packs) {
|
|
|
1897
3318
|
}
|
|
1898
3319
|
}
|
|
1899
3320
|
|
|
1900
|
-
function
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
[--format text|json|md] [--lang en|zh]
|
|
1915
|
-
dislop patterns [file | -] [--stdin-filename <name>] [--angle <a,b>] [--lang en|zh] [--json]
|
|
1916
|
-
dislop packs [--json]
|
|
1917
|
-
dislop resources [--json]
|
|
1918
|
-
dislop pack-test
|
|
1919
|
-
dislop init
|
|
1920
|
-
dislop --mcp`);
|
|
3321
|
+
function readGitBaselineForFile(absFile, gitRef = "HEAD") {
|
|
3322
|
+
const fileDir = path.dirname(absFile);
|
|
3323
|
+
const topLevel = execFileSync("git", ["-c", "core.quotepath=off", "rev-parse", "--show-toplevel"], {
|
|
3324
|
+
cwd: fileDir,
|
|
3325
|
+
encoding: "utf8",
|
|
3326
|
+
}).trim();
|
|
3327
|
+
const realFile = fs.realpathSync(absFile);
|
|
3328
|
+
const realTop = fs.realpathSync(topLevel);
|
|
3329
|
+
const relPosix = path.relative(realTop, realFile).split(path.sep).join("/");
|
|
3330
|
+
return execFileSync("git", ["-c", "core.quotepath=off", "show", `${gitRef}:${relPosix}`], {
|
|
3331
|
+
cwd: realTop,
|
|
3332
|
+
encoding: "utf8",
|
|
3333
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
3334
|
+
});
|
|
1921
3335
|
}
|
|
1922
3336
|
|
|
1923
|
-
|
|
1924
|
-
const
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
if (argv.includes("--mcp")) {
|
|
1929
|
-
runMcpServer(packs, patternByRuleId);
|
|
3337
|
+
function runVerify(args, packs) {
|
|
3338
|
+
const { flags, positional } = parseFlags(args, "verify");
|
|
3339
|
+
if (flags.help) {
|
|
3340
|
+
printSubcommandHelp("verify");
|
|
1930
3341
|
return;
|
|
1931
3342
|
}
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
3343
|
+
const cwd = process.cwd();
|
|
3344
|
+
const format = flags.json ? "json" : flags.format || "text";
|
|
3345
|
+
assertTextOrJsonFormat(format);
|
|
3346
|
+
const lang = flags.lang || "en";
|
|
3347
|
+
if (!["en", "zh"].includes(lang)) {
|
|
3348
|
+
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
3349
|
+
process.exit(2);
|
|
1935
3350
|
}
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
3351
|
+
const allowAdded = Boolean(flags["allow-added"]);
|
|
3352
|
+
const strict = Boolean(flags.strict);
|
|
3353
|
+
let flagRegister = null;
|
|
3354
|
+
if (flags.register !== undefined) {
|
|
3355
|
+
const norm = String(flags.register).trim().toLowerCase();
|
|
3356
|
+
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
3357
|
+
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
3358
|
+
process.exit(2);
|
|
3359
|
+
}
|
|
3360
|
+
flagRegister = norm;
|
|
1939
3361
|
}
|
|
3362
|
+
const keepRaw = typeof flags.keep === "string" ? flags.keep : "";
|
|
3363
|
+
const keepTerms = keepRaw ? keepRaw.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
3364
|
+
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
1940
3365
|
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
if (
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
3366
|
+
let beforeText;
|
|
3367
|
+
let afterText;
|
|
3368
|
+
let label;
|
|
3369
|
+
if (flags.git !== undefined) {
|
|
3370
|
+
let gitRef = "HEAD";
|
|
3371
|
+
let targetPath;
|
|
3372
|
+
if (flags.git === true) {
|
|
3373
|
+
targetPath = positional[0];
|
|
3374
|
+
} else if (positional.length === 0) {
|
|
3375
|
+
targetPath = String(flags.git);
|
|
3376
|
+
} else {
|
|
3377
|
+
gitRef = String(flags.git);
|
|
3378
|
+
targetPath = positional[0];
|
|
3379
|
+
}
|
|
3380
|
+
if (!targetPath) {
|
|
3381
|
+
console.error("Usage: dislop verify --git [ref] <file> [--keep a,b] [--pack <id|auto>] [--strict] [--json]");
|
|
3382
|
+
process.exit(2);
|
|
3383
|
+
}
|
|
3384
|
+
const absTarget = path.resolve(cwd, targetPath);
|
|
3385
|
+
if (!fs.existsSync(absTarget) || !fs.statSync(absTarget).isFile()) {
|
|
3386
|
+
console.error(`dislop: file not found: ${targetPath}`);
|
|
3387
|
+
process.exit(2);
|
|
3388
|
+
}
|
|
3389
|
+
label = targetPath;
|
|
3390
|
+
afterText = decodeUtf8Strict(fs.readFileSync(absTarget));
|
|
3391
|
+
try {
|
|
3392
|
+
beforeText = readGitBaselineForFile(absTarget, gitRef);
|
|
3393
|
+
} catch (err) {
|
|
3394
|
+
console.error(`dislop verify: failed to read '${gitRef}' baseline for '${targetPath}': ${err.message}`);
|
|
3395
|
+
process.exit(2);
|
|
3396
|
+
}
|
|
3397
|
+
} else {
|
|
3398
|
+
if (positional.length < 2) {
|
|
3399
|
+
console.error("Usage: dislop verify <before-file> <after-file> [--keep a,b] [--pack <id|auto>] [--strict] [--json]");
|
|
3400
|
+
process.exit(2);
|
|
3401
|
+
}
|
|
3402
|
+
const beforeAbs = path.resolve(cwd, positional[0]);
|
|
3403
|
+
const afterAbs = path.resolve(cwd, positional[1]);
|
|
3404
|
+
for (const [p, rawArg] of [[beforeAbs, positional[0]], [afterAbs, positional[1]]]) {
|
|
3405
|
+
if (!fs.existsSync(p) || !fs.statSync(p).isFile()) {
|
|
3406
|
+
console.error(`dislop: file not found: ${rawArg}`);
|
|
3407
|
+
process.exit(2);
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
label = positional[1];
|
|
3411
|
+
beforeText = decodeUtf8Strict(fs.readFileSync(beforeAbs));
|
|
3412
|
+
afterText = decodeUtf8Strict(fs.readFileSync(afterAbs));
|
|
3413
|
+
}
|
|
3414
|
+
|
|
3415
|
+
const mod = detectModality(label) || "markdown";
|
|
3416
|
+
const fileCfg = resolveConfigForFile(label, config);
|
|
3417
|
+
let resolvedPack;
|
|
3418
|
+
try {
|
|
3419
|
+
resolvedPack = resolveTextPackAndSource(afterText, label, mod, flags.pack || "auto", fileCfg, packs);
|
|
3420
|
+
} catch (err) {
|
|
3421
|
+
console.error(`dislop: ${err.message}`);
|
|
3422
|
+
process.exit(2);
|
|
3423
|
+
}
|
|
3424
|
+
const result = verifyRevisionBundle(beforeText, afterText, {
|
|
3425
|
+
filename: label,
|
|
3426
|
+
modality: mod,
|
|
3427
|
+
pack: resolvedPack.pack,
|
|
3428
|
+
config: fileCfg,
|
|
3429
|
+
register: flagRegister,
|
|
3430
|
+
keepTerms,
|
|
3431
|
+
allowAdded,
|
|
3432
|
+
strict,
|
|
3433
|
+
});
|
|
3434
|
+
result.effectivePack = resolvedPack.effectivePack;
|
|
3435
|
+
result.packSource = resolvedPack.packSource;
|
|
3436
|
+
|
|
3437
|
+
if (format === "json") {
|
|
3438
|
+
console.log(JSON.stringify(result, null, 2));
|
|
3439
|
+
} else {
|
|
3440
|
+
const fl = result.factLedger;
|
|
3441
|
+
const lc = result.lengthCheck;
|
|
3442
|
+
const ad = result.antiDegradation;
|
|
3443
|
+
if (lang === "zh") {
|
|
3444
|
+
console.log(`dislop verify (${label}): ${result.ok ? "通过 (PASSED)" : "未通过 (FAILED)"}`);
|
|
3445
|
+
console.log(` 事实账本 : ${fl.status}(保留 ${fl.retainedCount}/${fl.totalProtected},丢失 ${fl.missing.length},限定词降级 ${fl.qualifierDropped.length})`);
|
|
3446
|
+
if (result.keepTerms.requested.length > 0) {
|
|
3447
|
+
console.log(` 关键词保留: 保留 ${result.keepTerms.kept.length}/${result.keepTerms.requested.length}${result.keepTerms.missing.length ? `(缺失:${result.keepTerms.missing.join(", ")})` : ""}`);
|
|
3448
|
+
}
|
|
3449
|
+
if (result.findingsDelta) {
|
|
3450
|
+
console.log(` AI味变化 : ${result.findingsDelta.beforeCount} -> ${result.findingsDelta.afterCount}(消解 ${result.findingsDelta.resolvedCount},新引入 ${result.findingsDelta.introduced.length})`);
|
|
3451
|
+
}
|
|
3452
|
+
console.log(` 篇幅比例 : ${lc.beforeChars} -> ${lc.afterChars} 字(${lc.ratio}x · ${lc.status})`);
|
|
3453
|
+
console.log(` 反退化校验: ${ad.status}`);
|
|
3454
|
+
for (const w of ad.warnings) {
|
|
3455
|
+
console.log(` - [${w.severity.toUpperCase()}] ${w.code}: ${w.message.zh}`);
|
|
3456
|
+
}
|
|
3457
|
+
} else {
|
|
3458
|
+
console.log(`dislop verify (${label}): ${result.status.toUpperCase()}`);
|
|
3459
|
+
console.log(` Fact ledger : ${fl.status} (${fl.retainedCount}/${fl.totalProtected} retained, ${fl.missing.length} missing, ${fl.qualifierDropped.length} qualifier dropped)`);
|
|
3460
|
+
if (result.keepTerms.requested.length > 0) {
|
|
3461
|
+
console.log(` Keep terms : ${result.keepTerms.kept.length}/${result.keepTerms.requested.length} kept${result.keepTerms.missing.length ? ` (missing: ${result.keepTerms.missing.join(", ")})` : ""}`);
|
|
3462
|
+
}
|
|
3463
|
+
if (result.findingsDelta) {
|
|
3464
|
+
console.log(` Findings delta: ${result.findingsDelta.beforeCount} -> ${result.findingsDelta.afterCount} (${result.findingsDelta.resolvedCount} resolved, ${result.findingsDelta.introduced.length} introduced)`);
|
|
3465
|
+
}
|
|
3466
|
+
console.log(` Length ratio : ${lc.beforeChars} -> ${lc.afterChars} chars (${lc.ratio}x · ${lc.status})`);
|
|
3467
|
+
console.log(` Anti-degrade : ${ad.status}`);
|
|
3468
|
+
for (const w of ad.warnings) {
|
|
3469
|
+
console.log(` - [${w.severity.toUpperCase()}] ${w.code}: ${w.message.en}`);
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
}
|
|
3473
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
3474
|
+
}
|
|
3475
|
+
|
|
3476
|
+
const REVIEW_RESLOP_ZH_RE = /(?:全闭环|闭环|严禁|杜绝|赋能|抓手|家人们|绝绝子|其实吧|咱就是说|不是[^。\n]{1,30}而是)/g;
|
|
3477
|
+
const REVIEW_RESLOP_EN_RE = /\b(?:not\s+just\b[^.\n]{1,35}\bbut\b|game[- ]changing|seamless|delve\s+into|tapestry|let\s+that\s+sink\s+in)\b/gi;
|
|
3478
|
+
const VALID_TIC_LAYERS = new Set(["lexical", "syntactic", "rhythm", "cognitive-framing", "rhetorical-stance", "visual", "artifact"]);
|
|
3479
|
+
|
|
3480
|
+
function loadAiTicRubric(customPatternsDir = PATTERNS_DIR) {
|
|
3481
|
+
const p = path.join(customPatternsDir, "ai-tic-rubric.json");
|
|
3482
|
+
try {
|
|
3483
|
+
if (fs.existsSync(p)) {
|
|
3484
|
+
return JSON.parse(fs.readFileSync(p, "utf8"));
|
|
3485
|
+
}
|
|
3486
|
+
} catch {}
|
|
3487
|
+
return { layers: [], antiDegradationPrinciples: { en: [], zh: [] } };
|
|
3488
|
+
}
|
|
3489
|
+
|
|
3490
|
+
function mapFindingToTicLayer(finding) {
|
|
3491
|
+
const rid = String(finding?.ruleId || "");
|
|
3492
|
+
const dim = String(finding?.dimension || "");
|
|
3493
|
+
const fam = String(finding?.family || "");
|
|
3494
|
+
if (rid.startsWith("core/") || fam.startsWith("hygiene/") || fam.startsWith("office/") || dim === "artifacts") return "artifact";
|
|
3495
|
+
if (rid.startsWith("ui-") || rid.startsWith("pptx-") || fam.startsWith("deck/") || fam.startsWith("ui/") || dim === "visual-and-deck") return "visual";
|
|
3496
|
+
if (
|
|
3497
|
+
dim === "rhythm" ||
|
|
3498
|
+
fam.startsWith("rhythm/") ||
|
|
3499
|
+
fam.startsWith("punctuation/") ||
|
|
3500
|
+
["low-burstiness-vapor", "comma-chain-runon", "opener-anaphora-monotony", "inline-bold-saturation", "paragraph-length-uniformity", "semicolon-tricolon", "em-dash-cluster", "en-dash-overuse", "bold-lead-list-wall"].includes(rid)
|
|
3501
|
+
) {
|
|
3502
|
+
return "rhythm";
|
|
3503
|
+
}
|
|
3504
|
+
if (
|
|
3505
|
+
dim === "syntactic" ||
|
|
3506
|
+
fam.startsWith("frame/") ||
|
|
3507
|
+
["negation-pivot", "staccato-slogan-run", "zh-four-char-triad", "concession-symmetry-frame", "rhetorical-qa-cadence", "pull-quote-closer", "template-skeleton-echo"].includes(rid)
|
|
3508
|
+
) {
|
|
3509
|
+
return "syntactic";
|
|
3510
|
+
}
|
|
3511
|
+
if (
|
|
3512
|
+
["macro-trend-opener", "moralizing-ending", "narrative-sandwich", "unsourced-attribution", "unsubstantiated-superlative", "composite-multi-signal"].includes(rid) ||
|
|
3513
|
+
fam.startsWith("evidence/")
|
|
3514
|
+
) {
|
|
3515
|
+
return "cognitive-framing";
|
|
3516
|
+
}
|
|
3517
|
+
if (["throat-clearing-opener", "sycophancy-residue", "hedge-cluster", "discourse-marker-cluster"].includes(rid) || dim === "discourse") {
|
|
3518
|
+
return "rhetorical-stance";
|
|
3519
|
+
}
|
|
3520
|
+
return "lexical";
|
|
3521
|
+
}
|
|
3522
|
+
|
|
3523
|
+
function buildCrossCheckSummary({ ruleFindings, patternFindings, profile, mlFindings, mergedFindings, modality }) {
|
|
3524
|
+
const signalsPresent = [];
|
|
3525
|
+
if (ruleFindings.length > 0) signalsPresent.push("rules");
|
|
3526
|
+
if (patternFindings.length > 0) signalsPresent.push("patterns");
|
|
3527
|
+
if (profile && ((profile.telemetryRisk?.score || 0) >= 15 || profile.structure?.lowBurstinessVapor)) {
|
|
3528
|
+
signalsPresent.push("profile");
|
|
3529
|
+
}
|
|
3530
|
+
if (mlFindings.length > 0) signalsPresent.push("pocket-ml");
|
|
3531
|
+
|
|
3532
|
+
const layerCounts = {};
|
|
3533
|
+
for (const f of mergedFindings) {
|
|
3534
|
+
const layer = mapFindingToTicLayer(f);
|
|
3535
|
+
layerCounts[layer] = (layerCounts[layer] || 0) + 1;
|
|
3536
|
+
}
|
|
3537
|
+
|
|
3538
|
+
const proseMods = new Set(["markdown", "text", "html", "svg"]);
|
|
3539
|
+
const hasSubtleProse = Boolean(proseMods.has(modality) && profile && (profile.sentenceCount || 0) >= 3);
|
|
3540
|
+
const suspectedSubtleLayers = hasSubtleProse && (signalsPresent.length > 0 || ruleFindings.length === 0)
|
|
3541
|
+
? ["cognitive-framing", "rhetorical-stance"]
|
|
3542
|
+
: [];
|
|
3543
|
+
const llmRecommended = Boolean(
|
|
3544
|
+
hasSubtleProse && ((profile.telemetryRisk?.score || 0) >= 15 || mlFindings.length > 0 || ruleFindings.length === 0)
|
|
3545
|
+
);
|
|
3546
|
+
|
|
3547
|
+
return {
|
|
3548
|
+
signalsPresent,
|
|
3549
|
+
multiSignalConfirmed: signalsPresent.length >= 2,
|
|
3550
|
+
layerCounts,
|
|
3551
|
+
suspectedSubtleLayers,
|
|
3552
|
+
llmRecommended,
|
|
3553
|
+
};
|
|
3554
|
+
}
|
|
3555
|
+
|
|
3556
|
+
function findingsToReviewIssues(findings, lang = "en") {
|
|
3557
|
+
return findings.map((f) => {
|
|
3558
|
+
const strategy = f.fixStrategy || deriveFixStrategy({ id: f.ruleId, family: f.family });
|
|
3559
|
+
const action = strategy === "delete" ? "edit" : strategy === "need-source" ? "ask" : "rewrite";
|
|
3560
|
+
const why = (f.message?.[lang] || f.message?.en || f.ruleId || "").trim();
|
|
3561
|
+
const guidance = (f.deletionTest?.[lang] || f.deletionTest?.en || why).trim();
|
|
3562
|
+
return {
|
|
3563
|
+
source: f.source || "rule",
|
|
3564
|
+
ruleId: f.ruleId,
|
|
3565
|
+
ticLayer: mapFindingToTicLayer(f),
|
|
3566
|
+
severity: f.severity,
|
|
3567
|
+
fixStrategy: strategy,
|
|
3568
|
+
action,
|
|
3569
|
+
line: f.line || 1,
|
|
3570
|
+
col: f.col || 1,
|
|
3571
|
+
quote: f.match || "",
|
|
3572
|
+
why,
|
|
3573
|
+
...(action === "edit"
|
|
3574
|
+
? { replacement: "" }
|
|
3575
|
+
: action === "ask"
|
|
3576
|
+
? { question: guidance }
|
|
3577
|
+
: { instruction: guidance }),
|
|
3578
|
+
};
|
|
3579
|
+
});
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
function groundByokLlmIssues(rawIssues, sourceText, lineStarts) {
|
|
3583
|
+
if (!Array.isArray(rawIssues)) return [];
|
|
3584
|
+
const src = String(sourceText || "");
|
|
3585
|
+
const out = [];
|
|
3586
|
+
for (const iss of rawIssues) {
|
|
3587
|
+
if (!iss || typeof iss !== "object") continue;
|
|
3588
|
+
const q = String(iss.quote || "").trim();
|
|
3589
|
+
if (!q) continue;
|
|
3590
|
+
const idx = src.indexOf(q);
|
|
3591
|
+
if (idx === -1) continue;
|
|
3592
|
+
let action = ["edit", "replace", "delete", "rewrite", "ask"].includes(iss.action) ? iss.action : "rewrite";
|
|
3593
|
+
if (action === "replace" || action === "delete") action = "edit";
|
|
3594
|
+
const rep = action === "edit" ? String(iss.replacement ?? "") : "";
|
|
3595
|
+
if (action === "edit" || iss.replacement) {
|
|
3596
|
+
let introducedSlop = false;
|
|
3597
|
+
const qLower = q.toLowerCase();
|
|
3598
|
+
for (const m of String(iss.replacement || "").matchAll(REVIEW_RESLOP_ZH_RE)) {
|
|
3599
|
+
if (!q.includes(m[0])) {
|
|
3600
|
+
introducedSlop = true;
|
|
3601
|
+
break;
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
if (!introducedSlop) {
|
|
3605
|
+
for (const m of String(iss.replacement || "").matchAll(REVIEW_RESLOP_EN_RE)) {
|
|
3606
|
+
if (!qLower.includes(m[0].toLowerCase())) {
|
|
3607
|
+
introducedSlop = true;
|
|
3608
|
+
break;
|
|
3609
|
+
}
|
|
3610
|
+
}
|
|
3611
|
+
}
|
|
3612
|
+
if (introducedSlop) continue;
|
|
3613
|
+
}
|
|
3614
|
+
let finalInstruction = String(iss.instruction || iss.why || "").trim();
|
|
3615
|
+
if (action === "edit") {
|
|
3616
|
+
const vr = verifyRevision(q, rep);
|
|
3617
|
+
if (vr.status !== "preserved") {
|
|
3618
|
+
action = "rewrite";
|
|
3619
|
+
if (!finalInstruction) finalInstruction = String(iss.why || "Keep all numbers and qualifiers intact while removing filler.");
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
const lc = lineStarts ? (() => {
|
|
3623
|
+
let lo = 0; let hi = lineStarts.length - 1;
|
|
3624
|
+
while (lo <= hi) { const mid = (lo + hi) >> 1; if (lineStarts[mid] <= idx) lo = mid + 1; else hi = mid - 1; }
|
|
3625
|
+
const li = Math.max(0, hi);
|
|
3626
|
+
return { line: li + 1, col: idx - lineStarts[li] + 1 };
|
|
3627
|
+
})() : { line: 1, col: 1 };
|
|
3628
|
+
out.push({
|
|
3629
|
+
source: "byok-llm",
|
|
3630
|
+
ruleId: null,
|
|
3631
|
+
...(VALID_TIC_LAYERS.has(iss.ticLayer) ? { ticLayer: iss.ticLayer } : {}),
|
|
3632
|
+
severity: ["error", "warning", "info"].includes(iss.severity) ? iss.severity : "warning",
|
|
3633
|
+
fixStrategy: action === "edit" ? (rep === "" ? "delete" : "rephrase") : action === "ask" ? "need-source" : "rephrase",
|
|
3634
|
+
action,
|
|
3635
|
+
line: lc.line,
|
|
3636
|
+
col: lc.col,
|
|
3637
|
+
quote: q,
|
|
3638
|
+
why: String(iss.why || "").trim(),
|
|
3639
|
+
...(action === "edit"
|
|
3640
|
+
? { replacement: rep }
|
|
3641
|
+
: action === "ask"
|
|
3642
|
+
? { question: String(iss.question || finalInstruction).trim() }
|
|
3643
|
+
: { instruction: finalInstruction }),
|
|
3644
|
+
});
|
|
3645
|
+
if (out.length >= 16) break;
|
|
3646
|
+
}
|
|
3647
|
+
return out;
|
|
3648
|
+
}
|
|
3649
|
+
|
|
3650
|
+
function buildRubricPromptDigest(rubric, lang = "en") {
|
|
3651
|
+
const isZh = lang === "zh";
|
|
3652
|
+
const layers = Array.isArray(rubric?.layers) ? rubric.layers : [];
|
|
3653
|
+
if (layers.length === 0) return "";
|
|
3654
|
+
return layers
|
|
3655
|
+
.map((layer) => {
|
|
3656
|
+
const name = layer.name?.[isZh ? "zh" : "en"] || layer.id;
|
|
3657
|
+
const prompt = layer.llmCheckPrompt?.[isZh ? "zh" : "en"] || "";
|
|
3658
|
+
const guards = (layer.falsePositiveGuards?.[isZh ? "zh" : "en"] || []).slice(0, 1).join("; ");
|
|
3659
|
+
return `- [${layer.id}] ${name}: ${prompt}${guards ? ` (Guard: ${guards})` : ""}`;
|
|
3660
|
+
})
|
|
3661
|
+
.join("\n");
|
|
3662
|
+
}
|
|
3663
|
+
|
|
3664
|
+
async function runRubricReview(flags, positional, packs) {
|
|
3665
|
+
const cwd = process.cwd();
|
|
3666
|
+
const format = flags.json ? "json" : flags.format || "text";
|
|
3667
|
+
assertTextOrJsonFormat(format);
|
|
3668
|
+
const lang = flags.lang || "en";
|
|
3669
|
+
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
3670
|
+
const voiceInfo = discoverVoiceCard(cwd);
|
|
3671
|
+
const rubric = loadAiTicRubric();
|
|
3672
|
+
const target = positional[0] || "-";
|
|
3673
|
+
|
|
3674
|
+
let text;
|
|
3675
|
+
let label;
|
|
3676
|
+
if (target === "-") {
|
|
3677
|
+
text = readStdinTextChecked("review");
|
|
3678
|
+
label = detectStdinFilename(text, flags["stdin-filename"]);
|
|
3679
|
+
} else {
|
|
3680
|
+
const abs = path.resolve(cwd, target);
|
|
3681
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
3682
|
+
console.error(`dislop: file not found: ${target}`);
|
|
3683
|
+
process.exit(2);
|
|
3684
|
+
}
|
|
3685
|
+
label = target;
|
|
3686
|
+
text = decodeUtf8Strict(fs.readFileSync(abs));
|
|
3687
|
+
}
|
|
3688
|
+
|
|
3689
|
+
const mod = detectModality(label) || "markdown";
|
|
3690
|
+
const fileCfg = resolveConfigForFile(label, config);
|
|
3691
|
+
let flagRegister = null;
|
|
3692
|
+
if (flags.register !== undefined) {
|
|
3693
|
+
const norm = String(flags.register).trim().toLowerCase();
|
|
3694
|
+
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
3695
|
+
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
3696
|
+
process.exit(2);
|
|
3697
|
+
}
|
|
3698
|
+
flagRegister = norm;
|
|
3699
|
+
}
|
|
3700
|
+
const regInfo = resolveRegister(text, { filename: label, flagRegister, config: fileCfg });
|
|
3701
|
+
const packRes = resolveTextPackAndSource(text, label, mod, flags.pack || "auto", fileCfg, packs);
|
|
3702
|
+
const strategy = getScenarioStrategy({ packId: packRes.effectivePack, register: regInfo.register });
|
|
3703
|
+
const auditRes = auditText(text, { filename: label, modality: mod, pack: packRes.pack, config: fileCfg, register: regInfo.register });
|
|
3704
|
+
const ruleFindings = auditRes.findings;
|
|
3705
|
+
const patRes = auditPatterns(text, { filename: label, modality: mod, banks: loadPatternBanks(), config: fileCfg });
|
|
3706
|
+
const patternFindings = patRes.findings;
|
|
3707
|
+
let findings = mergePatternBankFindings(ruleFindings, patternFindings);
|
|
3708
|
+
const profile = PROSE_ML_MODALITIES.has(mod) ? analyzeTextProfile(text, { modality: mod, config: fileCfg }) : null;
|
|
3709
|
+
let mlFindings = [];
|
|
3710
|
+
if (PROSE_ML_MODALITIES.has(mod)) {
|
|
3711
|
+
const mlSrc = mod === "html" || mod === "svg" ? buildZones(text, mod, fileCfg).prose : text;
|
|
3712
|
+
mlFindings = buildPocketMlFindings(mlSrc, label, findings, null, { profile, modality: mod }).findings;
|
|
3713
|
+
findings = [...findings, ...mlFindings];
|
|
3714
|
+
}
|
|
3715
|
+
const crossCheck = buildCrossCheckSummary({
|
|
3716
|
+
ruleFindings,
|
|
3717
|
+
patternFindings,
|
|
3718
|
+
profile,
|
|
3719
|
+
mlFindings,
|
|
3720
|
+
mergedFindings: findings,
|
|
3721
|
+
modality: mod,
|
|
3722
|
+
});
|
|
3723
|
+
|
|
3724
|
+
const detIssues = findingsToReviewIssues(findings, lang);
|
|
3725
|
+
let issues = [...detIssues];
|
|
3726
|
+
let mode = "offline-deterministic";
|
|
3727
|
+
let summary =
|
|
3728
|
+
issues.length === 0
|
|
3729
|
+
? lang === "zh" ? "未发现确定性 AI 味或硬伤问题。" : "No deterministic AI-slop issues detected."
|
|
3730
|
+
: lang === "zh" ? `发现 ${issues.length} 处多信号审校建议(覆盖 ${crossCheck.signalsPresent.join("+") || "rules"},改后可用 dislop verify 校验)。` : `Found ${issues.length} multi-signal review item(s) across ${crossCheck.signalsPresent.join("+") || "rules"}.`;
|
|
3731
|
+
|
|
3732
|
+
const endpoint = flags.offline
|
|
3733
|
+
? ""
|
|
3734
|
+
: String(flags.endpoint || process.env.DISLOP_REVIEW_ENDPOINT || process.env.OPENAI_BASE_URL || "").trim();
|
|
3735
|
+
const keyEnvName = flags["api-key-env"]
|
|
3736
|
+
? String(flags["api-key-env"])
|
|
3737
|
+
: process.env.DISLOP_REVIEW_API_KEY
|
|
3738
|
+
? "DISLOP_REVIEW_API_KEY"
|
|
3739
|
+
: process.env.OPENAI_API_KEY
|
|
3740
|
+
? "OPENAI_API_KEY"
|
|
3741
|
+
: "";
|
|
3742
|
+
const apiKey = keyEnvName ? String(process.env[keyEnvName] || "") : "";
|
|
3743
|
+
|
|
3744
|
+
if (!flags.offline && endpoint && apiKey) {
|
|
3745
|
+
let u;
|
|
3746
|
+
try {
|
|
3747
|
+
u = new URL(endpoint);
|
|
3748
|
+
} catch {
|
|
3749
|
+
console.error(`dislop review: invalid endpoint URL '${endpoint}'`);
|
|
3750
|
+
process.exit(2);
|
|
3751
|
+
}
|
|
3752
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
3753
|
+
console.error(`dislop review: endpoint must use http or https scheme`);
|
|
3754
|
+
process.exit(2);
|
|
3755
|
+
}
|
|
3756
|
+
if (process.env.DISLOP_TEST_MODE === "1" && !["127.0.0.1", "localhost", "::1", "[::1]"].includes(u.hostname)) {
|
|
3757
|
+
console.error("dislop review: live BYOK requests are blocked when DISLOP_TEST_MODE=1");
|
|
3758
|
+
process.exit(2);
|
|
3759
|
+
}
|
|
3760
|
+
const chatUrl = endpoint.endsWith("/chat/completions") ? endpoint : `${endpoint.replace(/\/+$/, "")}/chat/completions`;
|
|
3761
|
+
const modelId = String(flags.model || process.env.DISLOP_REVIEW_MODEL || "gpt-4o-mini");
|
|
3762
|
+
const stratTag = lang === "zh" ? "zh" : "en";
|
|
3763
|
+
const sysPrompt =
|
|
3764
|
+
lang === "zh"
|
|
3765
|
+
? `你是 dislop 审校助手,请结合五层 AI 口癖准则与当前写作场景(${strategy.label.zh})交叉核对确定性预检与统计信号。本场景清理重点:${strategy.cut.zh};必须保留:${strategy.protect.zh};严禁改偏:${strategy.avoid.zh}。只输出 JSON:{"summary":"...","issues":[{"quote":"原文原样片段","ticLayer":"lexical|syntactic|rhythm|cognitive-framing|rhetorical-stance|visual|artifact","action":"edit|rewrite|ask","severity":"error|warning|info","why":"原因","replacement":"仅edit填","instruction":"仅rewrite填","question":"仅ask填"}]}。硬规则:1) 保留作者原有视角、自然句长起伏、个性化表达与带事实锚点的行业术语,禁止改写成死板说教、廉价“装人味”口水词(家人们/其实吧/绝绝子)或删减干货;2) quote 必须一字不差从原文复制;3) 禁止引入全闭环/闭环/赋能/抓手/不是A而是B等新套词;4) 绝不改丢数字或范围限定词(预计/仅在/除非/待确认)。`
|
|
3766
|
+
: `You are dislop's multi-layer AI-tic reviewer tuned for ${strategy.label.en} (${strategy.id}). Cut: ${strategy.cut.en} Protect: ${strategy.protect.en} Avoid: ${strategy.avoid.en} Cross-check deterministic findings and telemetry against the 5-layer rubric. Output strict JSON only: {"summary":"...","issues":[{"quote":"exact verbatim substring","ticLayer":"lexical|syntactic|rhythm|cognitive-framing|rhetorical-stance|visual|artifact","action":"edit|rewrite|ask","severity":"error|warning|info","why":"reason","replacement":"for edit","instruction":"for rewrite","question":"for ask"}]}. Rules: 1) preserve author voice, perspective, rhythm contrast, vivid phrasing, grounded domain terms, and modality qualifiers; never suggest cheesy fake-human slang; 2) quote MUST match verbatim; 3) never introduce filler slogans; 4) keep every number and unit intact.`;
|
|
3767
|
+
const rubricDigest = buildRubricPromptDigest(rubric, lang);
|
|
3768
|
+
const userPrompt = [
|
|
3769
|
+
`Modality: ${mod} | Pack: ${packRes.effectivePack} | Register: ${regInfo.register} | Scenario: ${strategy.id}`,
|
|
3770
|
+
`Scenario Strategy (${strategy.label[stratTag]}): cut=[${strategy.cut[stratTag]}] protect=[${strategy.protect[stratTag]}] avoid=[${strategy.avoid[stratTag]}]`,
|
|
3771
|
+
...(rubricDigest ? [`5-Layer AI-Tic Rubric:\n${rubricDigest}`] : []),
|
|
3772
|
+
`Local Cross-Check Signals: ${JSON.stringify(crossCheck)}`,
|
|
3773
|
+
...(voiceInfo.found && voiceInfo.card?.profile ? [`Author style card (${voiceInfo.scope}): ${JSON.stringify(voiceInfo.card.profile)}`] : []),
|
|
3774
|
+
`Deterministic findings: ${JSON.stringify(detIssues.slice(0, 12).map((x) => ({ ruleId: x.ruleId, ticLayer: x.ticLayer, quote: x.quote, fixStrategy: x.fixStrategy })))}`,
|
|
3775
|
+
`Draft:\n${text}`,
|
|
3776
|
+
].join("\n\n");
|
|
3777
|
+
try {
|
|
3778
|
+
const resp = await fetch(chatUrl, {
|
|
3779
|
+
method: "POST",
|
|
3780
|
+
headers: {
|
|
3781
|
+
"Content-Type": "application/json",
|
|
3782
|
+
Authorization: `Bearer ${apiKey}`,
|
|
3783
|
+
},
|
|
3784
|
+
body: JSON.stringify({
|
|
3785
|
+
model: modelId,
|
|
3786
|
+
temperature: 0.2,
|
|
3787
|
+
messages: [
|
|
3788
|
+
{ role: "system", content: sysPrompt },
|
|
3789
|
+
{ role: "user", content: userPrompt },
|
|
3790
|
+
],
|
|
3791
|
+
}),
|
|
3792
|
+
signal: AbortSignal.timeout(30000),
|
|
3793
|
+
});
|
|
3794
|
+
if (!resp.ok) {
|
|
3795
|
+
throw new Error(`HTTP ${resp.status}`);
|
|
3796
|
+
}
|
|
3797
|
+
const data = await resp.json();
|
|
3798
|
+
const rawContent = String(data?.choices?.[0]?.message?.content || "").trim();
|
|
3799
|
+
const jsonBody = rawContent.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
|
|
3800
|
+
const parsed = JSON.parse(jsonBody);
|
|
3801
|
+
const lineStarts = [0];
|
|
3802
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
3803
|
+
if (text[i] === "\n") lineStarts.push(i + 1);
|
|
3804
|
+
}
|
|
3805
|
+
const detQuotes = new Set(detIssues.map((d) => d.quote).filter(Boolean));
|
|
3806
|
+
const llmGrounded = groundByokLlmIssues(parsed?.issues, text, lineStarts).filter((i) => !detQuotes.has(i.quote));
|
|
3807
|
+
issues = [...detIssues, ...llmGrounded];
|
|
3808
|
+
mode = "byok-llm";
|
|
3809
|
+
if (typeof parsed?.summary === "string" && parsed.summary.trim()) {
|
|
3810
|
+
summary = parsed.summary.trim();
|
|
3811
|
+
}
|
|
3812
|
+
} catch (err) {
|
|
3813
|
+
console.error(`dislop review: endpoint call failed (${err.message})`);
|
|
3814
|
+
process.exit(2);
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
|
|
3818
|
+
const out = {
|
|
3819
|
+
schema: "dislop.review/1",
|
|
3820
|
+
mode,
|
|
3821
|
+
file: label,
|
|
3822
|
+
modality: mod,
|
|
3823
|
+
effectivePack: packRes.effectivePack,
|
|
3824
|
+
packSource: packRes.packSource,
|
|
3825
|
+
register: regInfo.register,
|
|
3826
|
+
scenarioStrategy: strategy.id,
|
|
3827
|
+
crossCheck,
|
|
3828
|
+
rubricLayers: (rubric.layers || []).map((l) => l.id),
|
|
3829
|
+
voiceCard: { found: voiceInfo.found, scope: voiceInfo.scope },
|
|
3830
|
+
...(profile ? { profile } : {}),
|
|
3831
|
+
summary,
|
|
3832
|
+
issues,
|
|
3833
|
+
};
|
|
3834
|
+
|
|
3835
|
+
if (format === "json") {
|
|
3836
|
+
console.log(JSON.stringify(out, null, 2));
|
|
3837
|
+
return;
|
|
3838
|
+
}
|
|
3839
|
+
const isZh = lang === "zh";
|
|
3840
|
+
const stratLabelsZh = { delete: "删掉", "need-source": "补出处", "unwrap-layout": "去套壳", rephrase: "改写" };
|
|
3841
|
+
const actLabelsZh = { edit: "修改", rewrite: "改写", ask: "核实" };
|
|
3842
|
+
const modeLabelZh = mode === "byok-llm" ? "本地+BYOK联合审校" : "四路离线核对";
|
|
3843
|
+
const vcNote = voiceInfo.found ? (isZh ? ` · 个人文风:${voiceInfo.scope}` : ` · voice:${voiceInfo.scope}`) : "";
|
|
3844
|
+
const layerStr = Object.entries(crossCheck.layerCounts)
|
|
3845
|
+
.map(([k, v]) => `${k}×${v}`)
|
|
3846
|
+
.join(", ") || (isZh ? "无明确命中" : "none");
|
|
3847
|
+
const sigStr = crossCheck.signalsPresent.join("+") || "rules";
|
|
3848
|
+
console.log(`dislop review (${label} · ${isZh ? modeLabelZh : mode} · ${packRes.effectivePack}${vcNote})`);
|
|
3849
|
+
console.log(isZh ? ` 摘要 : ${summary}` : ` summary : ${summary}`);
|
|
3850
|
+
console.log(isZh ? ` 信号分布: ${sigStr} | 层级: ${layerStr}` : ` signals : ${sigStr} | layers: ${layerStr}`);
|
|
3851
|
+
for (const iss of issues) {
|
|
3852
|
+
const tag = isZh ? stratLabelsZh[iss.fixStrategy] || iss.fixStrategy : iss.fixStrategy;
|
|
3853
|
+
const act = isZh ? actLabelsZh[iss.action] || iss.action : iss.action;
|
|
3854
|
+
const layerTag = iss.ticLayer ? ` · ${iss.ticLayer}` : "";
|
|
3855
|
+
console.log(` [${String(iss.severity).toUpperCase()}] ${iss.line}:${iss.col} ${act} (${tag}${layerTag}) "${iss.quote}"`);
|
|
3856
|
+
console.log(isZh ? ` 原因: ${iss.why}` : ` why: ${iss.why}`);
|
|
3857
|
+
if (iss.action === "edit") {
|
|
3858
|
+
console.log(isZh ? ` 替换: ${JSON.stringify(iss.replacement)}` : ` rep: ${JSON.stringify(iss.replacement)}`);
|
|
3859
|
+
} else if (iss.action === "ask") {
|
|
3860
|
+
console.log(isZh ? ` 追问: ${iss.question}` : ` ask: ${iss.question}`);
|
|
3861
|
+
} else if (iss.instruction && iss.instruction !== iss.why) {
|
|
3862
|
+
console.log(isZh ? ` 改法: ${iss.instruction}` : ` how: ${iss.instruction}`);
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
if (mode === "offline-deterministic" && crossCheck.llmRecommended) {
|
|
3866
|
+
console.log(
|
|
3867
|
+
isZh
|
|
3868
|
+
? " 深查提示: 思维“端水”(cognitive-framing)与说教角度(rhetorical-stance)可配 --endpoint 或云端 dislop_review 联合复核。"
|
|
3869
|
+
: " tip: Pass --endpoint (or use Cloud dislop_review) for LLM semantic cross-check on cognitive-framing and rhetorical-stance."
|
|
3870
|
+
);
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3873
|
+
|
|
3874
|
+
async function runProviderReview(flags, positional, packs) {
|
|
3875
|
+
if (positional.length > 1) {
|
|
3876
|
+
console.error("dislop review: inspect one file or '-' stdin per invocation.");
|
|
3877
|
+
process.exit(2);
|
|
3878
|
+
}
|
|
3879
|
+
const target = positional[0] || "-";
|
|
3880
|
+
const cwd = process.cwd();
|
|
3881
|
+
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
3882
|
+
const lang = flags.lang || "en";
|
|
3883
|
+
if (!["en", "zh"].includes(lang)) {
|
|
3884
|
+
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
3885
|
+
process.exit(2);
|
|
3886
|
+
}
|
|
3887
|
+
const format = flags.json ? "json" : flags.format || "text";
|
|
3888
|
+
if (!["text", "json", "agent"].includes(format)) {
|
|
3889
|
+
console.error(`dislop review: invalid --format '${format}' (expected text, json, or agent)`);
|
|
3890
|
+
process.exit(2);
|
|
3891
|
+
}
|
|
3892
|
+
const failOn = flags["fail-on"] || "warning";
|
|
3893
|
+
if (!SEVERITY_RANK[failOn]) {
|
|
3894
|
+
console.error(`dislop review: invalid --fail-on '${failOn}' (expected error, warning, info, or never)`);
|
|
3895
|
+
process.exit(2);
|
|
3896
|
+
}
|
|
3897
|
+
let timeoutMs = 30000;
|
|
3898
|
+
if (flags.timeout !== undefined) {
|
|
3899
|
+
const rawT = String(flags.timeout).trim();
|
|
3900
|
+
if (!/^\d+$/.test(rawT)) {
|
|
3901
|
+
console.error("dislop review: --timeout must be an integer between 1000 and 120000 ms");
|
|
3902
|
+
process.exit(2);
|
|
3903
|
+
}
|
|
3904
|
+
timeoutMs = Number(rawT);
|
|
3905
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 120000) {
|
|
3906
|
+
console.error("dislop review: --timeout must be between 1000 and 120000 ms");
|
|
3907
|
+
process.exit(2);
|
|
3908
|
+
}
|
|
3909
|
+
}
|
|
3910
|
+
let maxChunks = 20;
|
|
3911
|
+
if (flags["max-chunks"] !== undefined) {
|
|
3912
|
+
const rawC = String(flags["max-chunks"]).trim();
|
|
3913
|
+
if (!/^\d+$/.test(rawC)) {
|
|
3914
|
+
console.error("dislop review: --max-chunks must be an integer between 1 and 100");
|
|
3915
|
+
process.exit(2);
|
|
3916
|
+
}
|
|
3917
|
+
maxChunks = Number(rawC);
|
|
3918
|
+
if (!Number.isSafeInteger(maxChunks) || maxChunks < 1 || maxChunks > 100) {
|
|
3919
|
+
console.error("dislop review: --max-chunks must be between 1 and 100");
|
|
3920
|
+
process.exit(2);
|
|
3921
|
+
}
|
|
3922
|
+
}
|
|
3923
|
+
|
|
3924
|
+
let rawText = "";
|
|
3925
|
+
let filename = "stdin.md";
|
|
3926
|
+
let modality = "markdown";
|
|
3927
|
+
if (target === "-") {
|
|
3928
|
+
rawText = readStdinTextChecked("review");
|
|
3929
|
+
filename = detectStdinFilename(rawText, flags["stdin-filename"]);
|
|
3930
|
+
modality = detectModality(filename) || "markdown";
|
|
3931
|
+
if (flags["stdin-filename"] && (modality === "docx" || modality === "pptx" || modality === "pdf")) {
|
|
3932
|
+
console.error(`dislop review: '--stdin-filename' cannot treat stdin as binary '${modality}'; pass the file path directly.`);
|
|
3933
|
+
process.exit(2);
|
|
3934
|
+
}
|
|
3935
|
+
} else {
|
|
3936
|
+
const absPath = path.resolve(cwd, target);
|
|
3937
|
+
if (!fs.existsSync(absPath) || !fs.statSync(absPath).isFile()) {
|
|
3938
|
+
console.error(`dislop review: file not found: ${target}`);
|
|
3939
|
+
process.exit(2);
|
|
3940
|
+
}
|
|
3941
|
+
const rel = path.relative(cwd, absPath);
|
|
3942
|
+
filename =
|
|
3943
|
+
rel && !rel.startsWith("..") && !path.isAbsolute(rel)
|
|
3944
|
+
? rel.split(path.sep).join("/")
|
|
3945
|
+
: path.basename(absPath);
|
|
3946
|
+
modality = detectModality(absPath);
|
|
3947
|
+
if (!modality) {
|
|
3948
|
+
console.error(`dislop review: unsupported file type '${path.extname(absPath) || "(none)"}'`);
|
|
3949
|
+
process.exit(2);
|
|
3950
|
+
}
|
|
3951
|
+
const buf = fs.readFileSync(absPath);
|
|
3952
|
+
if (modality === "docx" || modality === "pptx") {
|
|
3953
|
+
try {
|
|
3954
|
+
const entries = readZipXmlEntries(buf);
|
|
3955
|
+
rawText = extractOoxmlReviewText(entries, modality, {
|
|
3956
|
+
includeNotes: Boolean(flags["include-notes"]),
|
|
3957
|
+
includeHidden: Boolean(flags["include-hidden"]),
|
|
3958
|
+
});
|
|
3959
|
+
} catch (err) {
|
|
3960
|
+
console.error(`dislop review: ${err.message}`);
|
|
3961
|
+
process.exit(2);
|
|
3962
|
+
}
|
|
3963
|
+
} else {
|
|
3964
|
+
try {
|
|
3965
|
+
rawText = decodeUtf8Strict(buf);
|
|
3966
|
+
} catch {
|
|
3967
|
+
console.error(`dislop review: '${target}' is not valid UTF-8 text`);
|
|
3968
|
+
process.exit(2);
|
|
3969
|
+
}
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
filename = String(filename).replace(/[\r\n]+/g, " ").trim() || "draft.md";
|
|
3973
|
+
|
|
3974
|
+
if (!rawText.trim()) {
|
|
3975
|
+
console.error("dislop review: extracted draft text is empty");
|
|
3976
|
+
process.exit(2);
|
|
3977
|
+
}
|
|
3978
|
+
|
|
3979
|
+
const flagRegister = flags.register !== undefined ? String(flags.register).trim().toLowerCase() : null;
|
|
3980
|
+
let regInfo;
|
|
3981
|
+
try {
|
|
3982
|
+
regInfo = resolveRegister(rawText, {
|
|
3983
|
+
filename,
|
|
3984
|
+
flagRegister,
|
|
3985
|
+
config,
|
|
3986
|
+
});
|
|
3987
|
+
} catch (err) {
|
|
3988
|
+
console.error(`dislop review: ${err.message}`);
|
|
3989
|
+
process.exit(2);
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3992
|
+
const packFlag = flags.pack === "auto" && (modality === "markdown" || modality === "text")
|
|
3993
|
+
? predictPackWithPocketRouter(rawText).recommendedPack
|
|
3994
|
+
: flags.pack === "auto"
|
|
3995
|
+
? null
|
|
3996
|
+
: flags.pack || null;
|
|
3997
|
+
const packId = pickPackForFile(filename, modality, packFlag, config);
|
|
3998
|
+
if (!packs[packId]) {
|
|
3999
|
+
console.error(`dislop review: unknown pack '${packId}'`);
|
|
4000
|
+
process.exit(2);
|
|
4001
|
+
}
|
|
4002
|
+
|
|
4003
|
+
let prov;
|
|
4004
|
+
const isDryRun = Boolean(flags["dry-run"]);
|
|
4005
|
+
const isPrintPrompt = Boolean(flags["print-prompt"]);
|
|
4006
|
+
try {
|
|
4007
|
+
prov = resolveProviderConfig({
|
|
4008
|
+
provider: flags.provider || process.env.DISLOP_REVIEW_PROVIDER || "openai",
|
|
4009
|
+
model: flags.model || null,
|
|
4010
|
+
baseUrl: flags["base-url"] || null,
|
|
4011
|
+
allowMissingKey: isDryRun || isPrintPrompt,
|
|
4012
|
+
env: process.env,
|
|
4013
|
+
});
|
|
4014
|
+
} catch (err) {
|
|
4015
|
+
console.error(`dislop review: ${err.message}`);
|
|
4016
|
+
process.exit(2);
|
|
4017
|
+
}
|
|
4018
|
+
|
|
4019
|
+
let chunks;
|
|
4020
|
+
try {
|
|
4021
|
+
chunks = chunkTextByParagraphs(rawText, 10000, { maxChunks });
|
|
4022
|
+
} catch (err) {
|
|
4023
|
+
console.error(`dislop review: ${err.message}`);
|
|
4024
|
+
process.exit(2);
|
|
4025
|
+
}
|
|
4026
|
+
|
|
4027
|
+
const firstPrompt = buildReviewPrompt({
|
|
4028
|
+
chunkText: chunks[0].text,
|
|
4029
|
+
filename,
|
|
4030
|
+
modality,
|
|
4031
|
+
packId,
|
|
4032
|
+
register: regInfo.register,
|
|
4033
|
+
lang,
|
|
4034
|
+
});
|
|
4035
|
+
const totalBytes = Buffer.byteLength(rawText, "utf8");
|
|
4036
|
+
const consentMode = prov.isLocal
|
|
4037
|
+
? "local-loopback"
|
|
4038
|
+
: flags.yes
|
|
4039
|
+
? "--yes"
|
|
4040
|
+
: process.env.DISLOP_ALLOW_REMOTE === "1"
|
|
4041
|
+
? "DISLOP_ALLOW_REMOTE=1"
|
|
4042
|
+
: "required";
|
|
4043
|
+
|
|
4044
|
+
if (isPrintPrompt) {
|
|
4045
|
+
if (format === "json") {
|
|
4046
|
+
console.log(
|
|
4047
|
+
JSON.stringify(
|
|
4048
|
+
{
|
|
4049
|
+
schema: "dislop.review-prompt/1",
|
|
4050
|
+
provider: prov.provider,
|
|
4051
|
+
host: prov.host,
|
|
4052
|
+
model: prov.model,
|
|
4053
|
+
chunks: chunks.length,
|
|
4054
|
+
bytes: totalBytes,
|
|
4055
|
+
delimiter: firstPrompt.delimiter,
|
|
4056
|
+
systemPrompt: firstPrompt.systemPrompt,
|
|
4057
|
+
userPrompt: firstPrompt.userPrompt,
|
|
4058
|
+
},
|
|
4059
|
+
null,
|
|
4060
|
+
2
|
|
4061
|
+
)
|
|
4062
|
+
);
|
|
4063
|
+
} else {
|
|
4064
|
+
console.log(`=== SYSTEM PROMPT ===\n${firstPrompt.systemPrompt}\n\n=== USER PROMPT (chunk 1/${chunks.length}) ===\n${firstPrompt.userPrompt}`);
|
|
4065
|
+
}
|
|
4066
|
+
return;
|
|
4067
|
+
}
|
|
4068
|
+
|
|
4069
|
+
if (isDryRun) {
|
|
4070
|
+
const dryPayload = {
|
|
4071
|
+
schema: "dislop.review-dry-run/1",
|
|
4072
|
+
provider: prov.provider,
|
|
4073
|
+
host: prov.host,
|
|
4074
|
+
endpointUrl: prov.safeUrl,
|
|
4075
|
+
model: prov.model,
|
|
4076
|
+
consent: consentMode,
|
|
4077
|
+
keyPresent: Boolean(prov.apiKey),
|
|
4078
|
+
keySource: prov.keySource,
|
|
4079
|
+
headers: {
|
|
4080
|
+
"content-type": "application/json",
|
|
4081
|
+
...(prov.apiKey ? { authorization: "Bearer <REDACTED>" } : {}),
|
|
4082
|
+
},
|
|
4083
|
+
file: filename,
|
|
4084
|
+
modality,
|
|
4085
|
+
pack: packId,
|
|
4086
|
+
context: regInfo,
|
|
4087
|
+
chunks: chunks.length,
|
|
4088
|
+
bytes: totalBytes,
|
|
4089
|
+
requestBody: {
|
|
4090
|
+
model: prov.model,
|
|
4091
|
+
temperature: 0,
|
|
4092
|
+
messages: [
|
|
4093
|
+
{ role: "system", content: firstPrompt.systemPrompt },
|
|
4094
|
+
{ role: "user", content: firstPrompt.userPrompt },
|
|
4095
|
+
],
|
|
4096
|
+
},
|
|
4097
|
+
};
|
|
4098
|
+
if (format === "json") {
|
|
4099
|
+
console.log(JSON.stringify(dryPayload, null, 2));
|
|
4100
|
+
} else if (lang === "zh") {
|
|
4101
|
+
console.log(`dislop review 演练(0 次网络请求)`);
|
|
4102
|
+
console.log(` 目标接口 : ${prov.safeUrl} (provider=${prov.provider}, model=${prov.model}, consent=${consentMode})`);
|
|
4103
|
+
console.log(` 鉴权来源 : ${prov.apiKey ? `环境变量 ${prov.keySource}(已脱敏)` : "未设置 / 本地免密钥"}`);
|
|
4104
|
+
console.log(` 待审文稿 : ${filename}(${totalBytes} 字节,${chunks.length} 段,语域=${regInfo.register})`);
|
|
4105
|
+
console.log(` 分隔标记 : ${firstPrompt.delimiter}`);
|
|
4106
|
+
} else {
|
|
4107
|
+
console.log(`dislop review dry-run: 0 network calls made`);
|
|
4108
|
+
console.log(` destination : ${prov.safeUrl} (provider=${prov.provider}, model=${prov.model}, consent=${consentMode})`);
|
|
4109
|
+
console.log(` auth : ${prov.apiKey ? `env ${prov.keySource} (redacted)` : "none/unset"}`);
|
|
4110
|
+
console.log(` draft : ${filename} (${totalBytes} bytes, ${chunks.length} chunk(s), register=${regInfo.register})`);
|
|
4111
|
+
console.log(` delimiter : ${firstPrompt.delimiter}`);
|
|
4112
|
+
}
|
|
4113
|
+
return;
|
|
4114
|
+
}
|
|
4115
|
+
|
|
4116
|
+
if (!prov.isLocal && Array.isArray(config?.forbid) && config.forbid.length > 0) {
|
|
4117
|
+
const hitLocs = [];
|
|
4118
|
+
for (const pat of config.forbid) {
|
|
4119
|
+
let re;
|
|
4120
|
+
try {
|
|
4121
|
+
re = new RegExp(pat, "gimu");
|
|
4122
|
+
} catch (err) {
|
|
4123
|
+
console.error(`dislop review: invalid .dislop.local.json forbid regex: ${err.message}`);
|
|
4124
|
+
process.exit(2);
|
|
4125
|
+
}
|
|
4126
|
+
if (re.test(filename)) {
|
|
4127
|
+
hitLocs.push("filename");
|
|
4128
|
+
}
|
|
4129
|
+
re.lastIndex = 0;
|
|
4130
|
+
let m;
|
|
4131
|
+
while ((m = re.exec(rawText)) !== null) {
|
|
4132
|
+
const lineNum = rawText.slice(0, m.index).split("\n").length;
|
|
4133
|
+
hitLocs.push(String(lineNum));
|
|
4134
|
+
if (hitLocs.length >= 20) break;
|
|
4135
|
+
if (m[0].length === 0) {
|
|
4136
|
+
if (re.lastIndex >= rawText.length) break;
|
|
4137
|
+
const cp = rawText.codePointAt(m.index);
|
|
4138
|
+
re.lastIndex = m.index + (cp !== undefined && cp > 0xffff ? 2 : 1);
|
|
4139
|
+
}
|
|
4140
|
+
}
|
|
4141
|
+
}
|
|
4142
|
+
if (hitLocs.length > 0) {
|
|
4143
|
+
const uniqueLocs = Array.from(new Set(hitLocs)).slice(0, 5).join(", ");
|
|
4144
|
+
console.error(
|
|
4145
|
+
`dislop review: refusing remote upload — matched ${hitLocs.length} local '.dislop.local.json' forbid policy hit(s) (${uniqueLocs}).`
|
|
4146
|
+
);
|
|
4147
|
+
process.exit(2);
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
4150
|
+
|
|
4151
|
+
if (prov.isLocal) {
|
|
4152
|
+
try {
|
|
4153
|
+
await assertLoopbackEndpoint(prov.hostname);
|
|
4154
|
+
} catch (err) {
|
|
4155
|
+
console.error(`dislop review: ${scrubSecrets(err.message, prov.apiKey ? [prov.apiKey] : [])}`);
|
|
4156
|
+
process.exit(2);
|
|
4157
|
+
}
|
|
4158
|
+
} else if (!flags.yes && process.env.DISLOP_ALLOW_REMOTE !== "1") {
|
|
4159
|
+
console.error(
|
|
4160
|
+
`dislop review: refusing remote upload without explicit confirmation (--yes or DISLOP_ALLOW_REMOTE=1).\n` +
|
|
4161
|
+
` target: host=${prov.host} provider=${prov.provider} model=${prov.model} file=${filename} bytes=${totalBytes} chunks=${chunks.length}`
|
|
4162
|
+
);
|
|
4163
|
+
process.exit(2);
|
|
4164
|
+
}
|
|
4165
|
+
|
|
4166
|
+
console.error(
|
|
4167
|
+
`dislop review: sending to host=${prov.host} provider=${prov.provider} model=${prov.model} file=${filename} bytes=${totalBytes} chunks=${chunks.length} register=${regInfo.register}`
|
|
4168
|
+
);
|
|
4169
|
+
|
|
4170
|
+
const allFindings = [];
|
|
4171
|
+
const seenFingerprints = new Set();
|
|
4172
|
+
const rejected = { ungroundedQuote: 0, inventedFact: 0, malformed: 0 };
|
|
4173
|
+
const summaries = [];
|
|
4174
|
+
const levels = [];
|
|
4175
|
+
let promptTokens = 0;
|
|
4176
|
+
let completionTokens = 0;
|
|
4177
|
+
let totalTokens = 0;
|
|
4178
|
+
let hasUsage = false;
|
|
4179
|
+
const redactList = prov.apiKey ? [prov.apiKey] : [];
|
|
4180
|
+
|
|
4181
|
+
for (const ch of chunks) {
|
|
4182
|
+
const prompt = ch.index === 0
|
|
4183
|
+
? firstPrompt
|
|
4184
|
+
: buildReviewPrompt({
|
|
4185
|
+
chunkText: ch.text,
|
|
4186
|
+
filename,
|
|
4187
|
+
modality,
|
|
4188
|
+
packId,
|
|
4189
|
+
register: regInfo.register,
|
|
4190
|
+
lang,
|
|
4191
|
+
});
|
|
4192
|
+
try {
|
|
4193
|
+
const apiRes = await runReviewRequest({
|
|
4194
|
+
endpointUrl: prov.endpointUrl,
|
|
4195
|
+
isLocal: prov.isLocal,
|
|
4196
|
+
hostname: prov.hostname,
|
|
4197
|
+
model: prov.model,
|
|
4198
|
+
apiKey: prov.apiKey,
|
|
4199
|
+
systemPrompt: prompt.systemPrompt,
|
|
4200
|
+
userPrompt: prompt.userPrompt,
|
|
4201
|
+
timeoutMs,
|
|
4202
|
+
});
|
|
4203
|
+
if (apiRes.usage && typeof apiRes.usage === "object" && !Array.isArray(apiRes.usage)) {
|
|
4204
|
+
try {
|
|
4205
|
+
const MAX_TOK = 1_000_000_000;
|
|
4206
|
+
const safeCount = (v) => {
|
|
4207
|
+
if (typeof v === "number") {
|
|
4208
|
+
return Number.isSafeInteger(v) && v >= 0 && v <= MAX_TOK ? v : 0;
|
|
4209
|
+
}
|
|
4210
|
+
if (typeof v === "string") {
|
|
4211
|
+
const s = v.trim();
|
|
4212
|
+
if (/^\d{1,10}$/.test(s)) {
|
|
4213
|
+
const n = Number(s);
|
|
4214
|
+
return Number.isSafeInteger(n) && n <= MAX_TOK ? n : 0;
|
|
4215
|
+
}
|
|
4216
|
+
}
|
|
4217
|
+
return 0;
|
|
4218
|
+
};
|
|
4219
|
+
const pt = safeCount(apiRes.usage.prompt_tokens);
|
|
4220
|
+
const ct = safeCount(apiRes.usage.completion_tokens);
|
|
4221
|
+
const tt = safeCount(apiRes.usage.total_tokens);
|
|
4222
|
+
hasUsage = true;
|
|
4223
|
+
promptTokens += pt;
|
|
4224
|
+
completionTokens += ct;
|
|
4225
|
+
totalTokens += tt;
|
|
4226
|
+
} catch {}
|
|
4227
|
+
}
|
|
4228
|
+
const norm = validateAndNormalizeReviewResponse({
|
|
4229
|
+
rawContent: apiRes.content,
|
|
4230
|
+
chunkText: ch.text,
|
|
4231
|
+
fullText: rawText,
|
|
4232
|
+
chunkStartOffset: ch.startOffset,
|
|
4233
|
+
filename,
|
|
4234
|
+
modality,
|
|
4235
|
+
lang,
|
|
4236
|
+
redactSecrets: redactList,
|
|
4237
|
+
});
|
|
4238
|
+
for (const f of norm.findings) {
|
|
4239
|
+
if (!seenFingerprints.has(f.fingerprint)) {
|
|
4240
|
+
seenFingerprints.add(f.fingerprint);
|
|
4241
|
+
allFindings.push(f);
|
|
4242
|
+
}
|
|
4243
|
+
}
|
|
4244
|
+
rejected.ungroundedQuote += norm.rejected.ungroundedQuote;
|
|
4245
|
+
rejected.inventedFact += norm.rejected.inventedFact;
|
|
4246
|
+
rejected.malformed += norm.rejected.malformed;
|
|
4247
|
+
if (norm.summary) summaries.push(norm.summary);
|
|
4248
|
+
levels.push(norm.aiFlavorLevel);
|
|
4249
|
+
} catch (err) {
|
|
4250
|
+
console.error(`dislop review: chunk ${ch.index + 1}/${chunks.length} failed — ${scrubSecrets(err.message, redactList)}`);
|
|
4251
|
+
process.exit(2);
|
|
4252
|
+
}
|
|
4253
|
+
}
|
|
4254
|
+
|
|
4255
|
+
const overallLevel = levels.includes("high") ? "high" : levels.includes("medium") ? "medium" : "low";
|
|
4256
|
+
const levelLabel = lang === "zh" ? ({ high: "高", medium: "中", low: "低" }[overallLevel] || overallLevel) : overallLevel;
|
|
4257
|
+
const summaryText = summaries.join(" ").trim();
|
|
4258
|
+
const usageSummary = hasUsage
|
|
4259
|
+
? { promptTokens, completionTokens, totalTokens }
|
|
4260
|
+
: null;
|
|
4261
|
+
const report = {
|
|
4262
|
+
schema: "dislop.review/1",
|
|
4263
|
+
version: ENGINE_VERSION,
|
|
4264
|
+
provider: prov.provider,
|
|
4265
|
+
host: prov.host,
|
|
4266
|
+
model: prov.model,
|
|
4267
|
+
file: filename,
|
|
4268
|
+
pack: packId,
|
|
4269
|
+
lang,
|
|
4270
|
+
chunks: chunks.length,
|
|
4271
|
+
bytes: totalBytes,
|
|
4272
|
+
aiFlavorLevel: overallLevel,
|
|
4273
|
+
summary: summaryText,
|
|
4274
|
+
context: { register: regInfo.register, registerSource: regInfo.registerSource },
|
|
4275
|
+
checkedCount: 1,
|
|
4276
|
+
skipped: [],
|
|
4277
|
+
findings: allFindings,
|
|
4278
|
+
unusedSuppressions: [],
|
|
4279
|
+
rejected,
|
|
4280
|
+
usage: usageSummary,
|
|
4281
|
+
};
|
|
4282
|
+
|
|
4283
|
+
if (format === "json") {
|
|
4284
|
+
console.log(JSON.stringify(report, null, 2));
|
|
4285
|
+
} else {
|
|
4286
|
+
const out = formatReport(report, format, lang, { failOn });
|
|
4287
|
+
console.log(out);
|
|
4288
|
+
if (format === "text" && summaryText) {
|
|
4289
|
+
console.log(lang === "zh" ? ` [综述 · ${levelLabel}] ${summaryText}` : ` [summary · ${overallLevel}] ${summaryText}`);
|
|
4290
|
+
}
|
|
4291
|
+
const rejTotal = rejected.ungroundedQuote + rejected.inventedFact + rejected.malformed;
|
|
4292
|
+
if (format === "text" && rejTotal > 0) {
|
|
4293
|
+
console.log(
|
|
4294
|
+
lang === "zh"
|
|
4295
|
+
? ` [校验过滤] 已丢弃 ${rejTotal} 条未通过核验的建议(无原文引用=${rejected.ungroundedQuote},编造事实=${rejected.inventedFact},格式异常=${rejected.malformed})`
|
|
4296
|
+
: ` [guard] filtered ${rejTotal} unverified suggestion(s) (ungrounded=${rejected.ungroundedQuote}, inventedFact=${rejected.inventedFact}, malformed=${rejected.malformed})`
|
|
4297
|
+
);
|
|
4298
|
+
}
|
|
4299
|
+
}
|
|
4300
|
+
const triggered = allFindings.some((f) => (SEVERITY_RANK[f.severity] || 1) >= SEVERITY_RANK[failOn]);
|
|
4301
|
+
process.exitCode = triggered ? 1 : 0;
|
|
4302
|
+
}
|
|
4303
|
+
|
|
4304
|
+
async function runReview(args, packs) {
|
|
4305
|
+
for (const tok of args) {
|
|
4306
|
+
if (tok === "--api-key" || tok.startsWith("--api-key=") || tok === "--token" || tok.startsWith("--token=")) {
|
|
4307
|
+
console.error(
|
|
4308
|
+
"dislop review: passing --api-key or --token as CLI arguments is forbidden (exposed via process list); set DISLOP_REVIEW_API_KEY or the provider env var instead."
|
|
4309
|
+
);
|
|
4310
|
+
process.exit(2);
|
|
4311
|
+
}
|
|
4312
|
+
}
|
|
4313
|
+
const { flags, positional } = parseFlags(args, "review");
|
|
4314
|
+
if (flags.help) {
|
|
4315
|
+
printSubcommandHelp("review");
|
|
4316
|
+
return;
|
|
4317
|
+
}
|
|
4318
|
+
if (flags.offline || flags.endpoint || flags["api-key-env"]) {
|
|
4319
|
+
return await runRubricReview(flags, positional, packs);
|
|
4320
|
+
}
|
|
4321
|
+
return await runProviderReview(flags, positional, packs);
|
|
4322
|
+
}
|
|
4323
|
+
|
|
4324
|
+
async function runDoctor(args, packs) {
|
|
4325
|
+
const { flags, positional } = parseFlags(args, "doctor");
|
|
4326
|
+
if (flags.help) {
|
|
4327
|
+
printSubcommandHelp("doctor");
|
|
4328
|
+
return;
|
|
4329
|
+
}
|
|
4330
|
+
if (positional.length > 0) {
|
|
4331
|
+
console.error(`dislop doctor: unexpected positional argument '${positional[0]}'.`);
|
|
4332
|
+
process.exit(2);
|
|
4333
|
+
}
|
|
4334
|
+
const lang = flags.lang || "en";
|
|
4335
|
+
if (!["en", "zh"].includes(lang)) {
|
|
4336
|
+
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
4337
|
+
process.exit(2);
|
|
4338
|
+
}
|
|
4339
|
+
const format = flags.json ? "json" : flags.format || "text";
|
|
4340
|
+
if (!["text", "json"].includes(format)) {
|
|
4341
|
+
console.error(`dislop doctor: invalid --format '${format}' (expected text or json)`);
|
|
4342
|
+
process.exit(2);
|
|
4343
|
+
}
|
|
4344
|
+
const cwd = process.cwd();
|
|
4345
|
+
let rulesCount = 0;
|
|
4346
|
+
for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
|
|
4347
|
+
const baseStatus = await buildModelStatusReport({
|
|
4348
|
+
packsCount: Object.keys(packs).length,
|
|
4349
|
+
rulesCount,
|
|
4350
|
+
probeLoopback: !flags["no-loopback"],
|
|
4351
|
+
cacheDir: flags["cache-dir"] || null,
|
|
4352
|
+
});
|
|
4353
|
+
|
|
4354
|
+
const skillRel = "skills/dislop/SKILL.md";
|
|
4355
|
+
const workspaceReady = fs.existsSync(path.join(cwd, skillRel));
|
|
4356
|
+
const bundledReady = fs.existsSync(path.join(REPO_ROOT, skillRel));
|
|
4357
|
+
const skillReady = workspaceReady || bundledReady;
|
|
4358
|
+
const byokEnv = inspectByokEnvStatus(process.env);
|
|
4359
|
+
const cfgPathFound = [".dislop.json", "dislop.json", ".disloprc.json", ".dislop.local.json"].some((n) =>
|
|
4360
|
+
fs.existsSync(path.join(cwd, n))
|
|
4361
|
+
);
|
|
4362
|
+
let cfgValid = true;
|
|
4363
|
+
let cfgError = null;
|
|
4364
|
+
try {
|
|
4365
|
+
loadConfig(cwd, null);
|
|
4366
|
+
} catch (err) {
|
|
4367
|
+
cfgValid = false;
|
|
4368
|
+
cfgError = scrubSecrets(err.message);
|
|
4369
|
+
}
|
|
4370
|
+
|
|
4371
|
+
let gitignoreLocalConfig = null;
|
|
4372
|
+
try {
|
|
4373
|
+
const g = spawnSync("git", ["check-ignore", "-q", ".dislop.local.json"], { cwd, encoding: "utf8", timeout: 2000 });
|
|
4374
|
+
if (g.status === 0) gitignoreLocalConfig = true;
|
|
4375
|
+
else if (g.status === 1) gitignoreLocalConfig = false;
|
|
4376
|
+
} catch {}
|
|
4377
|
+
|
|
4378
|
+
const ping = flags.online
|
|
4379
|
+
? await pingEndpointHealth("https://dislop.com/api/health")
|
|
4380
|
+
: { checked: false, ok: null, status: null, error: null };
|
|
4381
|
+
|
|
4382
|
+
const report = {
|
|
4383
|
+
...baseStatus,
|
|
4384
|
+
schema: "dislop.doctor/1",
|
|
4385
|
+
layers: {
|
|
4386
|
+
skill: { ready: skillReady, workspaceReady, bundledReady, path: skillRel },
|
|
4387
|
+
localCli: {
|
|
4388
|
+
ready: true,
|
|
4389
|
+
version: ENGINE_VERSION,
|
|
4390
|
+
packs: Object.keys(packs).length,
|
|
4391
|
+
rules: rulesCount,
|
|
4392
|
+
pocketMlReady: true,
|
|
4393
|
+
localRunnersCount: baseStatus.localRunners.length,
|
|
4394
|
+
},
|
|
4395
|
+
byokReview: byokEnv,
|
|
4396
|
+
officialCloudMcp: {
|
|
4397
|
+
url: "https://dislop.com/mcp",
|
|
4398
|
+
freeCreditsPerMonth: 30,
|
|
4399
|
+
ping,
|
|
4400
|
+
},
|
|
4401
|
+
config: {
|
|
4402
|
+
found: cfgPathFound,
|
|
4403
|
+
valid: cfgValid,
|
|
4404
|
+
error: cfgError,
|
|
4405
|
+
gitignoreLocalConfig,
|
|
4406
|
+
},
|
|
4407
|
+
},
|
|
4408
|
+
};
|
|
4409
|
+
|
|
4410
|
+
if (format === "json") {
|
|
4411
|
+
console.log(JSON.stringify(report, null, 2));
|
|
4412
|
+
if (!cfgValid) process.exitCode = 2;
|
|
4413
|
+
return;
|
|
4414
|
+
}
|
|
4415
|
+
|
|
4416
|
+
const configuredNames = Object.entries(byokEnv.providers)
|
|
4417
|
+
.filter(([, v]) => v.keyPresent)
|
|
4418
|
+
.map(([k, v]) => `${k}(${v.keySource})`);
|
|
4419
|
+
const hw = report.hardware;
|
|
4420
|
+
const rec = report.recommendation;
|
|
4421
|
+
if (lang === "zh") {
|
|
4422
|
+
const skillLabel = workspaceReady ? "已就绪(当前工作区)" : bundledReady ? "已就绪(安装包内置)" : "未找到";
|
|
4423
|
+
const pingLabel = ping.checked
|
|
4424
|
+
? (ping.ok ? `在线连通 HTTP ${ping.status}` : `连通失败:${ping.error || `HTTP ${ping.status}`}`)
|
|
4425
|
+
: (ping.error ? `已拦截(${ping.error})` : "未联网检测,可加 --online");
|
|
4426
|
+
console.log(`dislop doctor v${ENGINE_VERSION}(三层体检 · 默认 0 联网)`);
|
|
4427
|
+
console.log(` 1. 纯文档 Skill : ${skillLabel} (${skillRel})`);
|
|
4428
|
+
console.log(` 2. 本地 CLI 引擎 : 已就绪(${Object.keys(packs).length} 套规则包 / ${rulesCount} 条规则 · 14.6 KB Pocket ML · ${baseStatus.localRunners.length} 个本地推理端)`);
|
|
4429
|
+
console.log(` 硬件与选装推荐 : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB 内存 -> ${rec.tier}${rec.modelId ? ` (${rec.modelId})` : "(内置模型即可)"}`);
|
|
4430
|
+
console.log(` BYOK 深度审校 : ${configuredNames.length > 0 ? `已配置 ${configuredNames.join("、")}` : "未配置密钥环境变量(仅按需 --yes 启用)"}`);
|
|
4431
|
+
console.log(` 3. 官方云端 MCP : https://dislop.com/mcp(免费额度 30 次/月 · ${pingLabel})`);
|
|
4432
|
+
console.log(` 配置与隐私边界 : 配置=${cfgPathFound ? (cfgValid ? "有效" : `异常:${cfgError}`) : "使用默认"} | .dislop.local.json 忽略=${gitignoreLocalConfig === true ? "已忽略" : gitignoreLocalConfig === false ? "未加入 .gitignore" : "非 git 仓库"}`);
|
|
4433
|
+
} else {
|
|
4434
|
+
const skillLabel = workspaceReady ? "ready (workspace)" : bundledReady ? "ready (bundled)" : "not found";
|
|
4435
|
+
const pingLabel = ping.checked
|
|
4436
|
+
? (ping.ok ? `reachable HTTP ${ping.status}` : `unreachable: ${ping.error || `HTTP ${ping.status}`}`)
|
|
4437
|
+
: (ping.error ? `blocked (${ping.error})` : "offline (pass --online to ping)");
|
|
4438
|
+
console.log(`dislop doctor v${ENGINE_VERSION} (3-layer readiness · offline by default)`);
|
|
4439
|
+
console.log(` 1. Pure-doc Skill : ${skillLabel} (${skillRel})`);
|
|
4440
|
+
console.log(` 2. Local CLI/ML : ready (${Object.keys(packs).length} packs / ${rulesCount} rules · 14.6 KB Pocket ML · ${baseStatus.localRunners.length} local runner(s))`);
|
|
4441
|
+
console.log(` Hardware fit : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB RAM -> ${rec.tier}${rec.modelId ? ` (${rec.modelId})` : " (bundled only)"}`);
|
|
4442
|
+
console.log(` BYOK review : ${configuredNames.length > 0 ? `configured: ${configuredNames.join(", ")}` : "no API key env set (explicit opt-in only)"}`);
|
|
4443
|
+
console.log(` 3. Cloud MCP : https://dislop.com/mcp (30 free/mo · ${pingLabel})`);
|
|
4444
|
+
console.log(` Config & hygiene : config=${cfgPathFound ? (cfgValid ? "valid" : `invalid (${cfgError})`) : "defaults"} | .dislop.local.json gitignored=${gitignoreLocalConfig === null ? "n/a" : String(gitignoreLocalConfig)}`);
|
|
4445
|
+
}
|
|
4446
|
+
if (!cfgValid) process.exitCode = 2;
|
|
4447
|
+
}
|
|
4448
|
+
|
|
4449
|
+
function printHelp() {
|
|
4450
|
+
console.log(`dislop v${ENGINE_VERSION} — Cutting AI slop is real productivity. Linter for AI Slop in docs, web UI, and slides
|
|
4451
|
+
|
|
4452
|
+
Usage: dislop <command> [options]
|
|
4453
|
+
|
|
4454
|
+
Check & fix (local, 0 network calls):
|
|
4455
|
+
check [paths... | -] Audit files or stdin [--pack <id|auto>] [--register <id|auto>] [--deep] [-q|--quiet]
|
|
4456
|
+
[--fail-on error|warning|info|never] [--format text|json|agent|sarif|github|md]
|
|
4457
|
+
[--changed [ref] | --staged] [--rule <id,...>] [--lang en|zh]
|
|
4458
|
+
verify <before> <after> Verify edits retain numbers/qualifiers & --keep terms [--git [ref] <file>] [--strict]
|
|
4459
|
+
explain <rule-id> Show rationale, deletion test, and bad/trap/good examples
|
|
4460
|
+
init Create starter .dislop.json and gitignore .dislop.local.json
|
|
4461
|
+
|
|
4462
|
+
Browse rules & style:
|
|
4463
|
+
catalog [query] Search the 53-rule AI-slop catalog (alias: search)
|
|
4464
|
+
packs List bundled rule packs and supported formats
|
|
4465
|
+
patterns [file | -] Run multi-angle extended pattern-bank scan
|
|
4466
|
+
voice [paths... | -] Extract offline dislop.voice/1 writing profile
|
|
4467
|
+
|
|
4468
|
+
Agent & review:
|
|
4469
|
+
review [file | -] Multi-layer review (--offline | --endpoint <url> | --provider openai|gemini|local)
|
|
4470
|
+
--mcp Run local stdio MCP server (7 offline tools)
|
|
4471
|
+
resources Show bundled packs, static agent links, and Official Cloud MCP
|
|
4472
|
+
|
|
4473
|
+
Diagnostics & optional local models:
|
|
4474
|
+
doctor [--online] Check 3-layer readiness (Skill, Local CLI/ML, BYOK env, config, and optional Cloud ping)
|
|
4475
|
+
model [action] Manage/score Pocket ML & optional local models (status|score|install|import|remove|deslop)
|
|
4476
|
+
pack-test Validate Pack Schema v2 manifests and embedded fixtures
|
|
4477
|
+
|
|
4478
|
+
Exit codes: 0 clean | 1 findings >= --fail-on | 2 usage, config, or unreadable file error
|
|
4479
|
+
Example: dislop check draft.md --deep --lang zh`);
|
|
4480
|
+
}
|
|
4481
|
+
|
|
4482
|
+
async function main() {
|
|
4483
|
+
const argv = process.argv.slice(2);
|
|
4484
|
+
const packs = loadAllPacks();
|
|
4485
|
+
const patternByRuleId = loadPatternLibrary();
|
|
4486
|
+
|
|
4487
|
+
if (argv.includes("--mcp")) {
|
|
4488
|
+
runMcpServer(packs, patternByRuleId);
|
|
4489
|
+
return;
|
|
4490
|
+
}
|
|
4491
|
+
if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help" || argv[0] === "help") {
|
|
4492
|
+
if (argv[0] === "help" && argv[1]) {
|
|
4493
|
+
if (COMMAND_SPECS[argv[1]]) {
|
|
4494
|
+
printSubcommandHelp(argv[1]);
|
|
4495
|
+
return;
|
|
4496
|
+
}
|
|
4497
|
+
console.error(`dislop: unknown command '${argv[1]}'. Run 'dislop --help' for usage.`);
|
|
4498
|
+
process.exit(2);
|
|
4499
|
+
}
|
|
4500
|
+
printHelp();
|
|
4501
|
+
return;
|
|
4502
|
+
}
|
|
4503
|
+
if (argv[0] === "-v" || argv[0] === "--version") {
|
|
4504
|
+
console.log(ENGINE_VERSION);
|
|
4505
|
+
return;
|
|
4506
|
+
}
|
|
4507
|
+
|
|
4508
|
+
const cmd = argv[0];
|
|
4509
|
+
const rest = argv.slice(1);
|
|
4510
|
+
if (cmd === "check") return runCheck(rest, packs);
|
|
4511
|
+
if (cmd === "verify") return runVerify(rest, packs);
|
|
4512
|
+
if (cmd === "review") return await runReview(rest, packs);
|
|
4513
|
+
if (cmd === "voice") return runVoice(rest);
|
|
4514
|
+
if (cmd === "doctor") return await runDoctor(rest, packs);
|
|
4515
|
+
if (cmd === "model") return await runModel(rest, packs, "model");
|
|
4516
|
+
if (cmd === "setup") return await runModel(["setup", ...rest], packs, "setup");
|
|
4517
|
+
if (cmd === "deslop") {
|
|
4518
|
+
const { flags, positional } = parseFlags(rest, "deslop");
|
|
4519
|
+
if (flags.help) {
|
|
4520
|
+
printSubcommandHelp("deslop");
|
|
4521
|
+
return;
|
|
4522
|
+
}
|
|
1949
4523
|
if (!flags.local) {
|
|
1950
4524
|
console.error("dislop deslop: pass --local to run with a loopback local small model (0 external upload).");
|
|
1951
4525
|
process.exit(2);
|
|
@@ -1957,8 +4531,8 @@ async function main() {
|
|
|
1957
4531
|
if (cmd === "patterns") return runPatterns(rest);
|
|
1958
4532
|
if (cmd === "packs") return runPacks(rest, packs);
|
|
1959
4533
|
if (cmd === "resources") return runResources(rest, packs);
|
|
1960
|
-
if (cmd === "pack-test") return runPackTest(packs);
|
|
1961
|
-
if (cmd === "init") return runInit();
|
|
4534
|
+
if (cmd === "pack-test") return runPackTest(rest, packs);
|
|
4535
|
+
if (cmd === "init") return runInit(rest);
|
|
1962
4536
|
|
|
1963
4537
|
console.error(`dislop: unknown command '${cmd}'. Run 'dislop --help' for usage.`);
|
|
1964
4538
|
process.exit(2);
|