dislop 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +33 -0
  3. package/.claude-plugin/plugin.json +22 -0
  4. package/.codex-plugin/plugin.json +49 -0
  5. package/.mcp.json +12 -0
  6. package/.pre-commit-hooks.yaml +13 -0
  7. package/LICENSE +202 -0
  8. package/README.md +222 -2
  9. package/README.zh-CN.md +219 -0
  10. package/action.yml +90 -0
  11. package/assets/logo.svg +8 -0
  12. package/bin/dislop-mcp.mjs +5 -0
  13. package/bin/dislop.mjs +1967 -0
  14. package/gemini-extension.json +13 -0
  15. package/mcp.json +13 -0
  16. package/models/manifest.json +90 -0
  17. package/models/pocket-slop-v1.json +1 -0
  18. package/package.json +89 -4
  19. package/packs/business-brief/pack.json +598 -0
  20. package/packs/core/pack.json +192 -0
  21. package/packs/deck-and-ui/pack.json +290 -0
  22. package/packs/engineering-spec/pack.json +144 -0
  23. package/packs/executive-deck/pack.json +98 -0
  24. package/packs/literary-essay/pack.json +324 -0
  25. package/packs/regulated-comms/pack.json +99 -0
  26. package/patterns/README.md +39 -0
  27. package/patterns/banks/composite-fusion.json +36 -0
  28. package/patterns/banks/discourse-rhythm.json +95 -0
  29. package/patterns/banks/lexical-signals.json +74 -0
  30. package/patterns/banks/syntactic-frames.json +45 -0
  31. package/patterns/banks/visual-deck.json +37 -0
  32. package/patterns/dimensions/artifacts.json +121 -0
  33. package/patterns/dimensions/discourse.json +412 -0
  34. package/patterns/dimensions/lexical.json +172 -0
  35. package/patterns/dimensions/rhythm.json +206 -0
  36. package/patterns/dimensions/syntactic.json +285 -0
  37. package/patterns/dimensions/visual-and-deck.json +322 -0
  38. package/patterns/taxonomy.json +112 -0
  39. package/plugin.json +41 -0
  40. package/server.json +50 -0
  41. package/skills/dislop/SKILL.md +60 -0
  42. package/skills/dislop/agents/openai.yaml +6 -0
  43. package/skills/dislop/references/business-and-rfc.md +26 -0
  44. package/skills/dislop/references/editorial-and-essay.md +20 -0
  45. package/skills/dislop/references/regulated-and-precision.md +27 -0
  46. package/skills/dislop/references/web-ui-and-deck.md +26 -0
  47. package/src/binary-node.mjs +85 -0
  48. package/src/core.mjs +2488 -0
  49. package/src/local-model.mjs +977 -0
  50. package/src/pattern-engine.mjs +853 -0
  51. package/src/pocket-model.mjs +707 -0
package/bin/dislop.mjs ADDED
@@ -0,0 +1,1967 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import readline from "node:readline";
5
+ import { execFileSync } from "node:child_process";
6
+ import { fileURLToPath } from "node:url";
7
+ import {
8
+ ENGINE_VERSION,
9
+ SEVERITY_RANK,
10
+ fnv1aHex,
11
+ detectModality,
12
+ defaultPackForModality,
13
+ resolveEffectivePack,
14
+ auditText,
15
+ auditOoxmlEntries,
16
+ analyzeTextProfile,
17
+ formatReport,
18
+ buildCatalog,
19
+ queryCatalog,
20
+ extractVoiceProfileOffline,
21
+ } from "../src/core.mjs";
22
+ import { analyzePatternProfile, auditPatterns } from "../src/pattern-engine.mjs";
23
+ import {
24
+ analyzeDocumentWithPocketModels,
25
+ predictPackWithPocketRouter,
26
+ } from "../src/pocket-model.mjs";
27
+ import {
28
+ LOCAL_MODEL_TIERS,
29
+ buildModelStatusReport,
30
+ installOptionalModel,
31
+ importLocalModelFile,
32
+ removeInstalledModel,
33
+ runLocalDeslop,
34
+ } from "../src/local-model.mjs";
35
+ import { readZipXmlEntries } from "../src/binary-node.mjs";
36
+
37
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
38
+ const REPO_ROOT = path.resolve(__dirname, "..");
39
+ const PACKS_DIR = path.join(REPO_ROOT, "packs");
40
+ const PATTERNS_DIR = path.join(REPO_ROOT, "patterns");
41
+
42
+ const DEFAULT_IGNORE_DIRS = new Set([
43
+ ".git",
44
+ "node_modules",
45
+ ".venv",
46
+ "venv",
47
+ "__pycache__",
48
+ ".pytest_cache",
49
+ ".mypy_cache",
50
+ ]);
51
+
52
+ function loadAllPacks(customPacksDir = PACKS_DIR) {
53
+ const packs = {};
54
+ if (!fs.existsSync(customPacksDir)) return packs;
55
+ for (const entry of fs.readdirSync(customPacksDir, { withFileTypes: true })) {
56
+ if (!entry.isDirectory()) continue;
57
+ const manifestPath = path.join(customPacksDir, entry.name, "pack.json");
58
+ if (fs.existsSync(manifestPath)) {
59
+ const data = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
60
+ packs[data.id] = data;
61
+ }
62
+ }
63
+ return packs;
64
+ }
65
+
66
+ function loadPatternLibrary(customPatternsDir = PATTERNS_DIR) {
67
+ const dimDir = path.join(customPatternsDir, "dimensions");
68
+ const byRuleId = {};
69
+ if (!fs.existsSync(dimDir)) return byRuleId;
70
+ for (const entry of fs.readdirSync(dimDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
71
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
72
+ const data = JSON.parse(fs.readFileSync(path.join(dimDir, entry.name), "utf8"));
73
+ const dim = data.dimension || null;
74
+ for (const pat of data.patterns || []) {
75
+ if (pat.ruleId) {
76
+ byRuleId[pat.ruleId] = { dimension: dim, ...pat };
77
+ }
78
+ }
79
+ }
80
+ return byRuleId;
81
+ }
82
+
83
+ function loadConfig(cwd = process.cwd(), explicitConfigPath = null) {
84
+ let base = {};
85
+ const candidates = explicitConfigPath
86
+ ? [path.resolve(cwd, explicitConfigPath)]
87
+ : [
88
+ path.join(cwd, ".dislop.json"),
89
+ path.join(cwd, "dislop.json"),
90
+ path.join(cwd, ".disloprc.json"),
91
+ ];
92
+
93
+ for (const candidate of candidates) {
94
+ if (fs.existsSync(candidate)) {
95
+ base = JSON.parse(fs.readFileSync(candidate, "utf8"));
96
+ break;
97
+ }
98
+ }
99
+
100
+ const localPath = path.join(cwd, ".dislop.local.json");
101
+ if (fs.existsSync(localPath)) {
102
+ const localCfg = JSON.parse(fs.readFileSync(localPath, "utf8"));
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
+ };
111
+ }
112
+ return base;
113
+ }
114
+
115
+ function expandBraces(pattern) {
116
+ const m = pattern.match(/\{([^{}]+)\}/);
117
+ if (!m) return [pattern];
118
+ const prefix = pattern.slice(0, m.index);
119
+ const suffix = pattern.slice(m.index + m[0].length);
120
+ return m[1].split(",").flatMap((part) => expandBraces(prefix + part.trim() + suffix));
121
+ }
122
+
123
+ function globToRegExp(glob) {
124
+ const norm = glob.replace(/\\/g, "/").replace(/^\.\//, "");
125
+ let rx = "^";
126
+ for (let i = 0; i < norm.length; i += 1) {
127
+ const ch = norm[i];
128
+ if (ch === "*" && norm[i + 1] === "*") {
129
+ if (norm[i + 2] === "/") {
130
+ rx += "(?:.+/)?";
131
+ i += 2;
132
+ } else {
133
+ rx += ".*";
134
+ i += 1;
135
+ }
136
+ } else if (ch === "*") {
137
+ rx += "[^/]*";
138
+ } else if (ch === "?") {
139
+ rx += "[^/]";
140
+ } else if ("+.^$|()[]{}".includes(ch)) {
141
+ rx += "\\" + ch;
142
+ } else {
143
+ rx += ch;
144
+ }
145
+ }
146
+ rx += "$";
147
+ return new RegExp(rx);
148
+ }
149
+
150
+ function matchesAnyGlob(relPosix, globs = []) {
151
+ const clean = relPosix.replace(/^\.\//, "");
152
+ return globs.flatMap(expandBraces).some((g) => globToRegExp(g).test(clean));
153
+ }
154
+
155
+ function pickPackForFile(relPosix, modality, explicitPack, config) {
156
+ if (explicitPack) return explicitPack;
157
+ for (const ov of config?.overrides || []) {
158
+ const patterns = Array.isArray(ov.files) ? ov.files : [ov.files];
159
+ if (ov.pack && matchesAnyGlob(relPosix, patterns)) {
160
+ return ov.pack;
161
+ }
162
+ }
163
+ if (config?.pack) return config.pack;
164
+ return defaultPackForModality(modality);
165
+ }
166
+
167
+ function decodeUtf8Strict(buffer) {
168
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
169
+ return decoder.decode(buffer);
170
+ }
171
+
172
+ function collectFiles(targetPaths, cwd, config) {
173
+ const realCwd = fs.existsSync(cwd) ? fs.realpathSync(cwd) : cwd;
174
+ const files = [];
175
+ const skipped = [];
176
+ const ignoreGlobs = config?.ignore || [];
177
+
178
+ // When running inside the dislop repo itself without custom config, skip intentional bad-example dirs
179
+ const isSelfRepo =
180
+ fs.existsSync(path.join(realCwd, "packs", "core", "pack.json")) &&
181
+ fs.existsSync(path.join(realCwd, "src", "core.mjs"));
182
+ const effectiveIgnores = isSelfRepo && ignoreGlobs.length === 0
183
+ ? ["packs/**", "tests/**", "scratch/**"]
184
+ : ignoreGlobs;
185
+
186
+ function walk(absPath, explicit) {
187
+ if (!fs.existsSync(absPath)) {
188
+ throw new Error(`Target path not found: ${absPath}`);
189
+ }
190
+ const canonicalPath = fs.realpathSync(absPath);
191
+ const stat = fs.statSync(canonicalPath);
192
+ const rawRel = path.relative(realCwd, canonicalPath);
193
+ const rel =
194
+ !rawRel || rawRel === "."
195
+ ? path.basename(canonicalPath)
196
+ : rawRel === ".." || rawRel.startsWith(`..${path.sep}`) || path.isAbsolute(rawRel)
197
+ ? path.basename(canonicalPath)
198
+ : rawRel.split(path.sep).join("/");
199
+
200
+ if (!explicit && matchesAnyGlob(rel, effectiveIgnores)) {
201
+ return;
202
+ }
203
+
204
+ if (stat.isDirectory()) {
205
+ const entries = fs
206
+ .readdirSync(canonicalPath, { withFileTypes: true })
207
+ .sort((a, b) => a.name.localeCompare(b.name));
208
+ for (const entry of entries) {
209
+ if (DEFAULT_IGNORE_DIRS.has(entry.name)) continue;
210
+ walk(path.join(canonicalPath, entry.name), false);
211
+ }
212
+ return;
213
+ }
214
+
215
+ if (!stat.isFile()) return;
216
+ const mod = detectModality(canonicalPath);
217
+ if (!mod) {
218
+ if (explicit) {
219
+ skipped.push({ file: rel, reason: `Unsupported file extension '${path.extname(canonicalPath) || "(none)"}'` });
220
+ }
221
+ return;
222
+ }
223
+ files.push({ absPath: canonicalPath, rel, modality: mod, explicit });
224
+ }
225
+
226
+ for (const t of targetPaths) {
227
+ walk(path.resolve(realCwd, t), true);
228
+ }
229
+ return { files, skipped };
230
+ }
231
+
232
+ function getChangedLineMap(cwd, gitRef, staged = false) {
233
+ const args = staged
234
+ ? ["diff", "--cached", "-U0", "--no-color"]
235
+ : ["diff", "-U0", "--no-color", gitRef || "HEAD"];
236
+ const diffOut = execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 32 * 1024 * 1024 });
237
+ const changed = new Map(); // relPath -> Set<line> | "ALL"
238
+ let currentFile = null;
239
+
240
+ for (const line of diffOut.split(/\r?\n/)) {
241
+ if (line.startsWith("diff --git ")) {
242
+ const dm = line.match(/^diff --git a\/.+ b\/(.+)$/);
243
+ currentFile = dm ? dm[1].trim() : null;
244
+ } else if (line.startsWith("+++ b/")) {
245
+ currentFile = line.slice(6).trim();
246
+ if (!changed.has(currentFile)) changed.set(currentFile, new Set());
247
+ } else if (line.startsWith("Binary files ") && currentFile) {
248
+ changed.set(currentFile, "ALL");
249
+ } else if (line.startsWith("@@ ") && currentFile) {
250
+ const m = line.match(/\+(\d+)(?:,(\d+))?/);
251
+ if (m) {
252
+ const start = Number(m[1]);
253
+ const count = m[2] !== undefined ? Number(m[2]) : 1;
254
+ const set = changed.get(currentFile);
255
+ if (set instanceof Set) {
256
+ for (let k = 0; k < Math.max(1, count); k += 1) {
257
+ set.add(start + k);
258
+ }
259
+ }
260
+ }
261
+ }
262
+ }
263
+ return changed;
264
+ }
265
+
266
+ function buildPocketMlFindings(text, filename, existingFindings, threshold = null) {
267
+ const doc = analyzeDocumentWithPocketModels(text, { threshold });
268
+ const extras = [];
269
+ for (const p of doc.paragraphs) {
270
+ if (!p.flagged) continue;
271
+ const overlapsExisting = existingFindings.some(
272
+ (f) => f.line >= p.startLine && f.line <= p.endLine
273
+ );
274
+ if (overlapsExisting) continue;
275
+ const pct = Math.round(p.slopProbability * 100);
276
+ const drvEn = p.topDrivers.map((d) => d.reason.en).join("; ") || "uniform abstract phrasing";
277
+ const drvZh = p.topDrivers.map((d) => d.reason.zh).join("、") || "句式与用词高度均质";
278
+ const loc = String(p.startLine);
279
+ const cleanExcerpt = String(p.excerpt || "");
280
+ const fp = `pocket-stealth-vapor:${fnv1aHex(`pocket-stealth-vapor|${cleanExcerpt.toLowerCase()}|${loc}`)}`;
281
+ extras.push({
282
+ fingerprint: fp,
283
+ ruleId: "pocket-stealth-vapor",
284
+ packId: "pocket-model",
285
+ severity: "warning",
286
+ tier: "taste",
287
+ family: "rhythm/pocket-stealth-vapor",
288
+ category: "statistical-vapor",
289
+ modality: detectModality(filename) || "markdown",
290
+ file: filename,
291
+ location: loc,
292
+ line: p.startLine,
293
+ col: 1,
294
+ endLine: p.endLine,
295
+ match: cleanExcerpt,
296
+ excerpt: cleanExcerpt,
297
+ mlProbability: p.slopProbability,
298
+ message: {
299
+ en: `Paragraph reads as predictable low-concreteness AI filler (${pct}% pocket-ML score: ${drvEn}).`,
300
+ zh: `段落呈高度可预测、低事实密度的温吞水套话(内置模型评分 ${pct}%:${drvZh})。`,
301
+ },
302
+ deletionTest: {
303
+ en: "Cut this paragraph or replace abstract cushion wrappers with one concrete event, number, file path, or direct action.",
304
+ zh: "删掉整段空泛铺垫,或把抽象缓冲外壳直接换成具体事件、数字、文件路径或明确动作。",
305
+ },
306
+ });
307
+ }
308
+ return { doc, findings: extras };
309
+ }
310
+
311
+ function summarizePocketForProfile(text) {
312
+ const doc = analyzeDocumentWithPocketModels(text);
313
+ return {
314
+ documentProbability: doc.documentProbability,
315
+ band: doc.wholeTextScore.band,
316
+ recommendedPack: doc.packRouter.recommendedPack,
317
+ flaggedCount: doc.flaggedCount,
318
+ };
319
+ }
320
+
321
+ function mergePatternBankFindings(existingFindings, patFindings) {
322
+ const seen = new Set(existingFindings.map((f) => `${f.ruleId}:${f.line}`));
323
+ const out = [...existingFindings];
324
+ for (const pf of patFindings || []) {
325
+ const key = `${pf.ruleId}:${pf.line}`;
326
+ if (seen.has(key)) continue;
327
+ seen.add(key);
328
+ out.push(pf);
329
+ }
330
+ return out;
331
+ }
332
+
333
+ function inspectSingleFile({ absPath, rel, modality }, packs, explicitPack, config, { includeMl = false, includePatterns = false, banks = null } = {}) {
334
+ const stat = fs.statSync(absPath);
335
+ if (stat.size > 25 * 1024 * 1024) {
336
+ return {
337
+ checked: false,
338
+ findings: [],
339
+ unusedSuppressions: [],
340
+ skipped: [{ file: rel, reason: "File exceeds 25 MB single-file inspection cap" }],
341
+ };
342
+ }
343
+
344
+ const buf = fs.readFileSync(absPath);
345
+
346
+ if (modality === "docx" || modality === "pptx") {
347
+ const resolvedExplicit = explicitPack === "auto" ? null : explicitPack;
348
+ const packId = pickPackForFile(rel, modality, resolvedExplicit, config);
349
+ const pack = resolveEffectivePack(packId, packs, config);
350
+ try {
351
+ const entries = readZipXmlEntries(buf);
352
+ const res = auditOoxmlEntries(entries, { filename: rel, modality, pack, config });
353
+ const missingCorePart = res.skipped.some((s) => s.file === rel);
354
+ let findings = res.findings;
355
+ if (includePatterns && !missingCorePart) {
356
+ const patRes = auditPatterns("", { filename: rel, modality, banks: banks || loadPatternBanks(), ooxml: entries });
357
+ findings = mergePatternBankFindings(findings, patRes.findings);
358
+ }
359
+ return { checked: !missingCorePart, findings, unusedSuppressions: [], skipped: res.skipped };
360
+ } catch (err) {
361
+ return {
362
+ checked: false,
363
+ findings: [],
364
+ unusedSuppressions: [],
365
+ skipped: [{ file: rel, reason: `Uninspectable ${modality.toUpperCase()} archive: ${err.message}` }],
366
+ };
367
+ }
368
+ }
369
+
370
+ let text;
371
+ try {
372
+ text = decodeUtf8Strict(buf);
373
+ } catch {
374
+ return {
375
+ checked: false,
376
+ findings: [],
377
+ unusedSuppressions: [],
378
+ skipped: [{ file: rel, reason: "Non-UTF-8 text encoding; convert to UTF-8 to inspect" }],
379
+ };
380
+ }
381
+
382
+ const effectiveExplicit =
383
+ explicitPack === "auto" && (modality === "markdown" || modality === "text")
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);
390
+
391
+ const res = auditText(text, { filename: rel, modality, pack, config });
392
+ let findings = res.findings;
393
+ if (includePatterns) {
394
+ const patRes = auditPatterns(text, { filename: rel, modality, banks: banks || loadPatternBanks() });
395
+ findings = mergePatternBankFindings(findings, patRes.findings);
396
+ }
397
+ if (includeMl && (modality === "markdown" || modality === "text")) {
398
+ const mlRes = buildPocketMlFindings(text, rel, findings);
399
+ findings = [...findings, ...mlRes.findings];
400
+ }
401
+ return { checked: true, findings, unusedSuppressions: res.unusedSuppressions, skipped: [] };
402
+ }
403
+
404
+ // ---------- Subcommands ----------
405
+
406
+ function parseFlags(args) {
407
+ const flags = {};
408
+ const positional = [];
409
+ const boolKeys = new Set([
410
+ "json",
411
+ "staged",
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
+ ]);
428
+ for (let i = 0; i < args.length; i += 1) {
429
+ const arg = args[i];
430
+ if (arg === "-") {
431
+ positional.push("-");
432
+ } else if (arg === "-h") {
433
+ flags.help = true;
434
+ } else if (arg === "-v") {
435
+ flags.version = true;
436
+ } else if (arg === "-o") {
437
+ if (i + 1 < args.length) {
438
+ flags.output = args[i + 1];
439
+ i += 1;
440
+ } else {
441
+ console.error("dislop: flag '-o' requires a file path");
442
+ process.exit(2);
443
+ }
444
+ } else if (arg.startsWith("-o=")) {
445
+ flags.output = arg.slice(3);
446
+ } else if (arg.startsWith("--")) {
447
+ const eq = arg.indexOf("=");
448
+ if (eq !== -1) {
449
+ const key = arg.slice(2, eq);
450
+ const val = arg.slice(eq + 1);
451
+ if (boolKeys.has(key)) {
452
+ const low = val.trim().toLowerCase();
453
+ if (low === "true" || low === "1" || low === "yes") {
454
+ flags[key] = true;
455
+ } else if (low === "false" || low === "0" || low === "no") {
456
+ flags[key] = false;
457
+ } else {
458
+ console.error(`dislop: flag '--${key}' does not accept value '${val}'`);
459
+ process.exit(2);
460
+ }
461
+ } else {
462
+ flags[key] = val;
463
+ }
464
+ } else {
465
+ const key = arg.slice(2);
466
+ if (boolKeys.has(key)) {
467
+ flags[key] = true;
468
+ } else if (key === "changed" && (i + 1 >= args.length || args[i + 1].startsWith("-"))) {
469
+ flags[key] = "HEAD";
470
+ } else if (i + 1 < args.length) {
471
+ flags[key] = args[i + 1];
472
+ i += 1;
473
+ } else {
474
+ flags[key] = true;
475
+ }
476
+ }
477
+ } else {
478
+ positional.push(arg);
479
+ }
480
+ }
481
+ if (flags.help) {
482
+ printHelp();
483
+ process.exit(0);
484
+ }
485
+ return { flags, positional };
486
+ }
487
+
488
+ function assertTextOrJsonFormat(format) {
489
+ if (!["text", "json"].includes(format)) {
490
+ console.error(`dislop: invalid --format '${format}' (expected text or json)`);
491
+ process.exit(2);
492
+ }
493
+ }
494
+
495
+ function runCheck(args, packs) {
496
+ const { flags, positional } = parseFlags(args);
497
+ const cwd = process.cwd();
498
+ const config = loadConfig(cwd, flags.config || null);
499
+ const format = flags.json ? "json" : flags.format || "text";
500
+ const failOn = flags["fail-on"] || config.failOn || "error";
501
+ const lang = flags.lang || "en";
502
+ const reportUnused = Boolean(flags["report-unused"]);
503
+ const includeProfile = Boolean(flags.profile);
504
+ const includeMl = Boolean(flags.ml);
505
+ const includePatterns = Boolean(flags.patterns);
506
+ const banks = includePatterns ? loadPatternBanks() : null;
507
+
508
+ const validFormats = new Set(["text", "json", "sarif", "github", "md"]);
509
+ if (!validFormats.has(format)) {
510
+ console.error(`dislop: invalid --format '${format}' (expected text, json, sarif, github, or md)`);
511
+ process.exit(2);
512
+ }
513
+ if (!SEVERITY_RANK[failOn]) {
514
+ console.error(`dislop: invalid --fail-on '${failOn}' (expected error, warning, info, or never)`);
515
+ process.exit(2);
516
+ }
517
+
518
+ // Stdin mode
519
+ if (positional.includes("-")) {
520
+ const stdinText = fs.readFileSync(0, "utf8");
521
+ const filename = flags["stdin-filename"] || "stdin.md";
522
+ const modality = detectModality(filename) || "markdown";
523
+ const effectiveExplicit =
524
+ flags.pack === "auto" && (modality === "markdown" || modality === "text")
525
+ ? predictPackWithPocketRouter(stdinText).recommendedPack
526
+ : flags.pack === "auto"
527
+ ? null
528
+ : flags.pack || null;
529
+ const packId = pickPackForFile(filename, modality, effectiveExplicit, config);
530
+ let pack;
531
+ try {
532
+ pack = resolveEffectivePack(packId, packs, config);
533
+ } catch (err) {
534
+ console.error(`dislop: ${err.message}`);
535
+ process.exit(2);
536
+ }
537
+ const res = auditText(stdinText, { filename, modality, pack, config });
538
+ let findings = res.findings;
539
+ if (includePatterns) {
540
+ const patRes = auditPatterns(stdinText, { filename, modality, banks });
541
+ findings = mergePatternBankFindings(findings, patRes.findings);
542
+ }
543
+ if (includeMl && (modality === "markdown" || modality === "text")) {
544
+ findings = [...findings, ...buildPocketMlFindings(stdinText, filename, findings).findings];
545
+ }
546
+ const report = {
547
+ version: ENGINE_VERSION,
548
+ checkedCount: 1,
549
+ skipped: [],
550
+ findings,
551
+ unusedSuppressions: reportUnused ? res.unusedSuppressions : [],
552
+ ...(includeProfile && (modality === "markdown" || modality === "text")
553
+ ? {
554
+ profiles: [
555
+ {
556
+ file: filename,
557
+ profile: analyzeTextProfile(stdinText, { modality }),
558
+ pocketModel: summarizePocketForProfile(stdinText),
559
+ },
560
+ ],
561
+ }
562
+ : {}),
563
+ };
564
+ console.log(formatReport(report, format, lang));
565
+ const triggered =
566
+ findings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
567
+ (reportUnused && res.unusedSuppressions.length > 0);
568
+ process.exitCode = triggered ? 1 : 0;
569
+ return;
570
+ }
571
+
572
+ let changedMap = null;
573
+ if (flags.changed || flags.staged) {
574
+ try {
575
+ changedMap = getChangedLineMap(cwd, typeof flags.changed === "string" ? flags.changed : "HEAD", Boolean(flags.staged));
576
+ } catch (err) {
577
+ console.error(`dislop: failed to read git diff: ${err.message}`);
578
+ process.exit(2);
579
+ }
580
+ }
581
+
582
+ const targets = positional.length > 0 ? positional : changedMap ? Array.from(changedMap.keys()).filter((p) => fs.existsSync(path.join(cwd, p))) : ["."];
583
+ let collected;
584
+ try {
585
+ collected = collectFiles(targets, cwd, config);
586
+ } catch (err) {
587
+ console.error(`dislop: ${err.message}`);
588
+ process.exit(2);
589
+ }
590
+
591
+ const allFindings = [];
592
+ const allSkipped = [...collected.skipped];
593
+ const allUnused = [];
594
+ const allProfiles = [];
595
+ let checkedCount = 0;
596
+ let explicitUninspectable = collected.skipped.length > 0;
597
+
598
+ for (const item of collected.files) {
599
+ if (changedMap && !changedMap.has(item.rel)) continue;
600
+ let res;
601
+ try {
602
+ res = inspectSingleFile(item, packs, flags.pack || null, config, { includeMl, includePatterns, banks });
603
+ } catch (err) {
604
+ console.error(`dislop: ${err.message}`);
605
+ process.exit(2);
606
+ }
607
+ if (res.checked) {
608
+ checkedCount += 1;
609
+ if (includeProfile && (item.modality === "markdown" || item.modality === "text")) {
610
+ try {
611
+ const rawTxt = decodeUtf8Strict(fs.readFileSync(item.absPath));
612
+ allProfiles.push({
613
+ file: item.rel,
614
+ profile: analyzeTextProfile(rawTxt, { modality: item.modality }),
615
+ pocketModel: summarizePocketForProfile(rawTxt),
616
+ });
617
+ } catch {}
618
+ }
619
+ } else if (item.explicit) {
620
+ explicitUninspectable = true;
621
+ }
622
+ let fileFindings = res.findings;
623
+ if (changedMap && changedMap.has(item.rel)) {
624
+ const allowedLines = changedMap.get(item.rel);
625
+ if (allowedLines instanceof Set) {
626
+ fileFindings = fileFindings.filter((f) => allowedLines.has(f.line));
627
+ }
628
+ }
629
+ allFindings.push(...fileFindings);
630
+ allSkipped.push(...res.skipped);
631
+ if (reportUnused) {
632
+ allUnused.push(...res.unusedSuppressions);
633
+ }
634
+ }
635
+
636
+ const report = {
637
+ version: ENGINE_VERSION,
638
+ checkedCount,
639
+ skipped: allSkipped,
640
+ findings: allFindings,
641
+ unusedSuppressions: allUnused,
642
+ ...(allProfiles.length > 0 ? { profiles: allProfiles } : {}),
643
+ };
644
+
645
+ const rendered = formatReport(report, format, lang);
646
+ if (rendered) console.log(rendered);
647
+
648
+ if (explicitUninspectable || (checkedCount === 0 && allSkipped.length > 0)) {
649
+ process.exitCode = 2;
650
+ return;
651
+ }
652
+ const shouldFail =
653
+ allFindings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
654
+ (reportUnused && allUnused.length > 0);
655
+ process.exitCode = shouldFail ? 1 : 0;
656
+ }
657
+
658
+ const POCKET_STEALTH_VAPOR_RULE = {
659
+ id: "pocket-stealth-vapor",
660
+ tier: "taste",
661
+ severity: "warning",
662
+ category: "statistical-vapor",
663
+ dimension: "discourse-rhythm",
664
+ family: "rhythm/pocket-stealth-vapor",
665
+ modalities: ["markdown", "text"],
666
+ tags: ["pocket-ml", "stealth-vapor", "low-concreteness", "flat-cadence"],
667
+ message: {
668
+ en: "Paragraph scores above the bundled 15 KB Pocket ML threshold for low-concreteness, uniform-cadence AI filler despite avoiding banned buzzwords.",
669
+ zh: "段落虽避开了禁用热词表,但在句长节奏、抽象名词化与低事实密度上命中内置 15 KB 轻量集成模型的温吞水套话阈值。",
670
+ },
671
+ deletionTest: {
672
+ en: "Cut this paragraph or replace abstract cushion wrappers with one concrete event, number, file path, or direct action.",
673
+ zh: "删掉整段空泛铺垫,或把抽象缓冲外壳直接换成具体事件、数字、文件路径或明确动作。",
674
+ },
675
+ exemplar: {
676
+ bad: "During ongoing collaboration, maintaining a steady rhythm across teams helps surface operational observations early while supporting long-term alignment.",
677
+ trap: "This isn't about more meetings — it's about radical operational clarity.",
678
+ good: "We post a 3-line status update in #release every Tuesday at 10:00 so blockers surface before Thursday's cut.",
679
+ source: "Original constructed example (Apache-2.0)",
680
+ },
681
+ };
682
+
683
+ function runExplain(args, packs, patternByRuleId) {
684
+ const { flags, positional } = parseFlags(args);
685
+ const format = flags.json ? "json" : flags.format || "text";
686
+ assertTextOrJsonFormat(format);
687
+ const ruleId = positional[0];
688
+ if (!ruleId) {
689
+ console.error("Usage: dislop explain <rule-id> [--lang en|zh] [--json]");
690
+ process.exit(2);
691
+ }
692
+ const lang = flags.lang || "en";
693
+ for (const pack of Object.values(packs)) {
694
+ const rule = (pack.rules || []).find((r) => r.id === ruleId);
695
+ if (rule) {
696
+ if (format === "json") {
697
+ console.log(JSON.stringify({ packId: pack.id, ...rule }, null, 2));
698
+ process.exit(0);
699
+ }
700
+ console.log(`${rule.id} [${rule.tier} / ${rule.severity}] (pack: ${pack.id})`);
701
+ console.log(`Modalities: ${(rule.modalities || []).join(", ")}`);
702
+ console.log(`Why: ${rule.message?.[lang] || rule.message?.en}`);
703
+ if (rule.deletionTest) {
704
+ console.log(`Test: ${rule.deletionTest[lang] || rule.deletionTest.en}`);
705
+ }
706
+ if (rule.exemplar) {
707
+ console.log(`\nBefore (bad): ${rule.exemplar.bad}`);
708
+ if (rule.exemplar.trap) {
709
+ console.log(`Trap (avoid): ${rule.exemplar.trap}`);
710
+ }
711
+ console.log(`After (good): ${rule.exemplar.good}`);
712
+ if (rule.exemplar.note) {
713
+ console.log(`Note: ${rule.exemplar.note[lang] || rule.exemplar.note.en}`);
714
+ }
715
+ }
716
+ process.exit(0);
717
+ }
718
+ }
719
+ const pat = patternByRuleId && patternByRuleId[ruleId];
720
+ if (pat) {
721
+ const sev = pat.severityDefault || "info";
722
+ const packId = pat.packId || "pattern-bank";
723
+ const msg = pat.mechanism || pat.name || { en: "", zh: "" };
724
+ const guards = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
725
+ const synth = {
726
+ packId,
727
+ id: ruleId,
728
+ tier: "taste",
729
+ severity: sev,
730
+ category: pat.category || "general",
731
+ dimension: pat.dimension || null,
732
+ modalities: pat.modalities || ["markdown", "text"],
733
+ tags: pat.tags || [],
734
+ message: msg,
735
+ ...(guards ? { deletionTest: { en: guards, zh: guards } } : {}),
736
+ ...(pat.exemplar ? { exemplar: pat.exemplar } : {}),
737
+ };
738
+ if (format === "json") {
739
+ console.log(JSON.stringify(synth, null, 2));
740
+ process.exit(0);
741
+ }
742
+ console.log(`${synth.id} [${synth.tier} / ${synth.severity}] (pack: ${packId})`);
743
+ console.log(`Modalities: ${synth.modalities.join(", ")}`);
744
+ console.log(`Why: ${msg[lang] || msg.en}`);
745
+ if (guards) console.log(`Guards: ${guards}`);
746
+ if (pat.exemplar) {
747
+ console.log(`\nBefore (bad): ${pat.exemplar.bad}`);
748
+ if (pat.exemplar.trap) console.log(`Trap (avoid): ${pat.exemplar.trap}`);
749
+ console.log(`After (good): ${pat.exemplar.good}`);
750
+ }
751
+ process.exit(0);
752
+ }
753
+ if (ruleId === "pocket-stealth-vapor") {
754
+ const r = POCKET_STEALTH_VAPOR_RULE;
755
+ if (format === "json") {
756
+ console.log(JSON.stringify({ packId: "pocket-model", ...r }, null, 2));
757
+ process.exit(0);
758
+ }
759
+ console.log(`${r.id} [${r.tier} / ${r.severity}] (pack: pocket-model)`);
760
+ console.log(`Modalities: ${r.modalities.join(", ")}`);
761
+ console.log(`Why: ${r.message[lang] || r.message.en}`);
762
+ console.log(`Test: ${r.deletionTest[lang] || r.deletionTest.en}`);
763
+ console.log(`\nBefore (bad): ${r.exemplar.bad}`);
764
+ console.log(`Trap (avoid): ${r.exemplar.trap}`);
765
+ console.log(`After (good): ${r.exemplar.good}`);
766
+ process.exit(0);
767
+ }
768
+ console.error(`dislop: unknown rule '${ruleId}'`);
769
+ process.exit(2);
770
+ }
771
+
772
+ function runPacks(args, packs) {
773
+ const { flags } = parseFlags(args);
774
+ const format = flags.json ? "json" : flags.format || "text";
775
+ assertTextOrJsonFormat(format);
776
+ const list = Object.values(packs).map((p) => ({
777
+ id: p.id,
778
+ version: p.version,
779
+ tier: p.tier,
780
+ extends: p.extends || [],
781
+ name: p.name,
782
+ modalities: p.modalities,
783
+ ruleCount: (p.rules || []).length,
784
+ summary: p.summary,
785
+ }));
786
+ if (format === "json") {
787
+ console.log(JSON.stringify(list, null, 2));
788
+ return;
789
+ }
790
+ for (const p of list) {
791
+ console.log(`${p.id.padEnd(18)} [${p.tier}] (${p.ruleCount} rules) — ${p.name.en} / ${p.name.zh}`);
792
+ console.log(` modalities: ${p.modalities.join(", ")}`);
793
+ }
794
+ }
795
+
796
+ const VALID_MODALITIES = new Set(["markdown", "text", "html", "css", "jsx", "svg", "docx", "pptx"]);
797
+ const VALID_SEVERITIES = new Set(["error", "warning", "info"]);
798
+ const VALID_TIERS = new Set(["invariant", "taste"]);
799
+
800
+ function runCatalog(args, packs, patternByRuleId) {
801
+ const { flags, positional } = parseFlags(args);
802
+ const format = flags.json ? "json" : flags.format || "text";
803
+ const lang = flags.lang || "en";
804
+ if (!["text", "json", "md"].includes(format)) {
805
+ console.error(`dislop: invalid --format '${format}' (expected text, json, or md)`);
806
+ process.exit(2);
807
+ }
808
+ if (flags.severity && !VALID_SEVERITIES.has(flags.severity)) {
809
+ console.error(`dislop: invalid --severity '${flags.severity}' (expected error, warning, or info)`);
810
+ process.exit(2);
811
+ }
812
+ if (flags.modality && !VALID_MODALITIES.has(flags.modality)) {
813
+ console.error(`dislop: invalid --modality '${flags.modality}'`);
814
+ process.exit(2);
815
+ }
816
+ if (flags.tier && !VALID_TIERS.has(flags.tier)) {
817
+ console.error(`dislop: invalid --tier '${flags.tier}' (expected invariant or taste)`);
818
+ process.exit(2);
819
+ }
820
+
821
+ const query = flags.query || positional.join(" ").trim() || "";
822
+ const limit = flags.limit ? Number(flags.limit) : null;
823
+ const entries = buildCatalog(packs, patternByRuleId);
824
+ const result = queryCatalog(entries, {
825
+ query,
826
+ pack: flags.pack || null,
827
+ category: flags.category || null,
828
+ dimension: flags.dimension || null,
829
+ family: flags.family || null,
830
+ modality: flags.modality || null,
831
+ severity: flags.severity || null,
832
+ tier: flags.tier || null,
833
+ includeExemplars: flags["no-exemplars"] ? false : true,
834
+ limit: Number.isInteger(limit) && limit > 0 ? limit : null,
835
+ });
836
+
837
+ if (format === "json") {
838
+ console.log(JSON.stringify(result, null, 2));
839
+ return;
840
+ }
841
+ if (format === "md") {
842
+ const rows = [
843
+ "| Rule | Pack | Severity | Category | Modalities | Description |",
844
+ "|---|---|---|---|---|---|",
845
+ ...result.items.map((item) => {
846
+ const msg = (item.message?.[lang] || item.message?.en || "").replace(/\|/g, "\\|");
847
+ return `| \`${item.id}\` | \`${item.packId}\` | \`${item.severity}\` | \`${item.category}\` | ${(item.modalities || []).join(", ")} | ${msg} |`;
848
+ }),
849
+ ];
850
+ console.log(rows.join("\n"));
851
+ return;
852
+ }
853
+
854
+ console.log(`dislop catalog: ${result.matched} / ${result.total} rule(s) matched`);
855
+ for (const item of result.items) {
856
+ const msg = item.message?.[lang] || item.message?.en || "";
857
+ console.log(` [${item.severity.padEnd(7)}] ${item.id.padEnd(30)} (${item.packId} · ${item.category}) — ${msg}`);
858
+ }
859
+ }
860
+
861
+ function runPackTest(packs) {
862
+ const errors = [];
863
+ let assertions = 0;
864
+
865
+ for (const pack of Object.values(packs)) {
866
+ if (pack.schema !== "dislop.pack/2") {
867
+ errors.push(`${pack.id}: expected schema 'dislop.pack/2'`);
868
+ }
869
+ const effective = resolveEffectivePack(pack.id, packs, {});
870
+ for (const rule of pack.rules || []) {
871
+ if (!rule.deletionTest?.en || !rule.deletionTest?.zh) {
872
+ errors.push(`${pack.id}/${rule.id}: missing bilingual deletionTest`);
873
+ }
874
+ if (!rule.exemplar?.bad || !rule.exemplar?.good || !rule.exemplar?.source) {
875
+ errors.push(`${pack.id}/${rule.id}: missing exemplar (bad/good/source)`);
876
+ }
877
+ const hits = rule.fixtures?.hit || [];
878
+ const cleans = rule.fixtures?.clean || [];
879
+ if (hits.length === 0 || cleans.length === 0) {
880
+ errors.push(`${pack.id}/${rule.id}: requires at least 1 hit and 1 clean fixture`);
881
+ }
882
+ const sampleMod = (rule.modalities && rule.modalities[0]) || "markdown";
883
+ for (const h of hits) {
884
+ assertions += 1;
885
+ const res = auditText(h, { filename: `fixture.${sampleMod}`, modality: sampleMod, pack: effective, allowSyntheticFixtures: true });
886
+ if (!res.findings.some((f) => f.ruleId === rule.id)) {
887
+ errors.push(`${pack.id}/${rule.id}: hit fixture did NOT trigger rule: ${JSON.stringify(h)}`);
888
+ }
889
+ }
890
+ for (const c of cleans) {
891
+ assertions += 1;
892
+ const res = auditText(c, { filename: `fixture.${sampleMod}`, modality: sampleMod, pack: effective, allowSyntheticFixtures: true });
893
+ if (res.findings.some((f) => f.ruleId === rule.id)) {
894
+ errors.push(`${pack.id}/${rule.id}: clean fixture FALSELY triggered rule: ${JSON.stringify(c)}`);
895
+ }
896
+ }
897
+ // Lint regex patterns against unbounded `.*`
898
+ for (const pat of rule.patterns || []) {
899
+ if (/\.\*/.test(pat)) {
900
+ errors.push(`${pack.id}/${rule.id}: unbounded '.*' forbidden in portable pack regex: ${pat}`);
901
+ }
902
+ }
903
+ }
904
+ }
905
+
906
+ if (errors.length > 0) {
907
+ console.error(`dislop pack-test: FAILED (${errors.length} error(s) across ${assertions} assertions)`);
908
+ for (const e of errors) console.error(` - ${e}`);
909
+ process.exit(1);
910
+ }
911
+ console.log(`dislop pack-test: ok (${Object.keys(packs).length} packs, ${assertions} fixture assertions passed)`);
912
+ }
913
+
914
+ function runInit() {
915
+ const cwd = process.cwd();
916
+ const cfgPath = path.join(cwd, ".dislop.json");
917
+ if (!fs.existsSync(cfgPath)) {
918
+ const starter = {
919
+ failOn: "error",
920
+ ignore: ["vendor/**", "dist/**"],
921
+ overrides: [{ files: ["docs/**/*.md"], pack: "business-brief" }],
922
+ allow: [],
923
+ rules: {},
924
+ };
925
+ fs.writeFileSync(cfgPath, JSON.stringify(starter, null, 2) + "\n", "utf8");
926
+ console.log(`Created ${cfgPath}`);
927
+ } else {
928
+ console.log(`${cfgPath} already exists`);
929
+ }
930
+
931
+ const giPath = path.join(cwd, ".gitignore");
932
+ const localEntry = ".dislop.local.json";
933
+ if (fs.existsSync(giPath)) {
934
+ const cur = fs.readFileSync(giPath, "utf8");
935
+ if (!cur.split(/\r?\n/).includes(localEntry)) {
936
+ fs.writeFileSync(giPath, cur.replace(/\s*$/, "\n") + localEntry + "\n", "utf8");
937
+ console.log(`Added ${localEntry} to .gitignore`);
938
+ }
939
+ }
940
+ }
941
+
942
+ // ---------- MCP Stdio Server ----------
943
+
944
+ function runMcpServer(packs, patternByRuleId) {
945
+ const cwd = process.cwd();
946
+ const config = loadConfig(cwd);
947
+ const catalogEntries = buildCatalog(packs, patternByRuleId);
948
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
949
+
950
+ function send(msg) {
951
+ process.stdout.write(JSON.stringify(msg) + "\n");
952
+ }
953
+
954
+ function toolResult(id, payload, isError = false) {
955
+ send({
956
+ jsonrpc: "2.0",
957
+ id,
958
+ result: {
959
+ isError,
960
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
961
+ },
962
+ });
963
+ }
964
+
965
+ function formatRuleForExplain(rule, packId, lang) {
966
+ const cleanLang = lang === "en" || lang === "zh" ? lang : null;
967
+ const localizeObj = (obj) => {
968
+ if (!obj || typeof obj !== "object") return obj;
969
+ if (!cleanLang) return obj;
970
+ return { [cleanLang]: obj[cleanLang] || obj.en || "" };
971
+ };
972
+ const out = {
973
+ packId,
974
+ id: rule.id,
975
+ tier: rule.tier,
976
+ severity: rule.severity,
977
+ ...(rule.category ? { category: rule.category } : {}),
978
+ ...(rule.family ? { family: rule.family } : {}),
979
+ modalities: rule.modalities || [],
980
+ ...(Array.isArray(rule.tags) ? { tags: rule.tags } : {}),
981
+ message: localizeObj(rule.message),
982
+ deletionTest: localizeObj(rule.deletionTest),
983
+ };
984
+ if (rule.exemplar) {
985
+ out.exemplar = {
986
+ ...rule.exemplar,
987
+ ...(rule.exemplar.note ? { note: localizeObj(rule.exemplar.note) } : {}),
988
+ };
989
+ }
990
+ return out;
991
+ }
992
+
993
+ function formatFindingsForMcp(findings, verbosity, lang) {
994
+ const cleanLang = lang === "en" || lang === "zh" ? lang : null;
995
+ const localizeObj = (obj) => {
996
+ if (!obj || typeof obj !== "object" || !cleanLang) return obj;
997
+ return { [cleanLang]: obj[cleanLang] || obj.en || "" };
998
+ };
999
+ if (verbosity === "full") {
1000
+ if (!cleanLang) return findings;
1001
+ return findings.map((f) => ({
1002
+ ...f,
1003
+ message: localizeObj(f.message),
1004
+ deletionTest: localizeObj(f.deletionTest),
1005
+ }));
1006
+ }
1007
+ return findings.map((f) => ({
1008
+ fingerprint: f.fingerprint,
1009
+ ruleId: f.ruleId,
1010
+ tier: f.tier ?? "taste",
1011
+ severity: f.severity,
1012
+ family: f.family ?? (f.dimension ? `${f.dimension}/${f.ruleId}` : null),
1013
+ file: f.file,
1014
+ modality: f.modality,
1015
+ location: f.location,
1016
+ line: f.line,
1017
+ col: f.col,
1018
+ match: f.match,
1019
+ message: localizeObj(f.message),
1020
+ deletionTest: f.deletionTest ? localizeObj(f.deletionTest) : null,
1021
+ }));
1022
+ }
1023
+
1024
+ const tools = [
1025
+ {
1026
+ name: "dislop_check",
1027
+ 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), and PowerPoint (.pptx). Edit only the flagged spans, then run `dislop_check` again.",
1029
+ inputSchema: {
1030
+ type: "object",
1031
+ properties: {
1032
+ 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)" },
1034
+ pack: { type: "string", description: "Style pack ID (auto, business-brief, engineering-spec, regulated-comms, literary-essay, deck-and-ui, executive-deck)" },
1035
+ filename: { type: "string", description: "Virtual filename hint when inspecting `text`" },
1036
+ profile: { type: "boolean", description: "Include 5-axis rhythm & concreteness telemetry on text/markdown (default true)" },
1037
+ ml: { type: "boolean", description: "Enable bundled 15 KB Pocket ML stealth-vapor paragraph detection (default false)" },
1038
+ patterns: { type: "boolean", description: "Include extended 6-dimension pattern-bank probes (default false)" },
1039
+ verbosity: { type: "string", enum: ["compact", "full"], description: "Default compact (omits per-hit exemplars to save context tokens; pass full to inline exemplars)" },
1040
+ lang: { type: "string", enum: ["en", "zh"], description: "Optional single-locale filter for finding messages" },
1041
+ },
1042
+ },
1043
+ },
1044
+ {
1045
+ name: "dislop_explain",
1046
+ description:
1047
+ "Retrieve the rationale, check question, and before/trap/after examples for a specific `ruleId`.",
1048
+ inputSchema: {
1049
+ type: "object",
1050
+ properties: {
1051
+ ruleId: { type: "string", description: "Rule ID returned by dislop_check or dislop_catalog" },
1052
+ lang: { type: "string", enum: ["en", "zh"], description: "en or zh" },
1053
+ },
1054
+ required: ["ruleId"],
1055
+ },
1056
+ },
1057
+ {
1058
+ name: "dislop_packs",
1059
+ description: "List installed rule packs, supported formats, and rule counts.",
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.",
1066
+ inputSchema: {
1067
+ type: "object",
1068
+ properties: {
1069
+ query: { type: "string", description: "Optional bilingual keyword query (matches id, tags, message, deletionTest, exemplar)" },
1070
+ pack: { type: "string" },
1071
+ category: { type: "string" },
1072
+ dimension: { type: "string" },
1073
+ family: { type: "string" },
1074
+ modality: { type: "string" },
1075
+ severity: { type: "string", enum: ["error", "warning", "info"] },
1076
+ tier: { type: "string", enum: ["invariant", "taste"] },
1077
+ lang: { type: "string", enum: ["en", "zh"] },
1078
+ includeExemplars: { type: "boolean", description: "Default true; set false for compact index listing" },
1079
+ limit: { type: "integer", minimum: 1, maximum: 100 },
1080
+ },
1081
+ },
1082
+ },
1083
+ {
1084
+ name: "dislop_voice_extract_offline",
1085
+ description:
1086
+ "Extract a deterministic offline `dislop.voice/1` statistical writing profile from 1-15 clean author samples (0 network calls, 0 uploads).",
1087
+ inputSchema: {
1088
+ type: "object",
1089
+ properties: {
1090
+ samples: {
1091
+ type: "array",
1092
+ items: { type: "string" },
1093
+ minItems: 1,
1094
+ maxItems: 15,
1095
+ description: "1 to 15 clean sample passages written by the author",
1096
+ },
1097
+ lang: { type: "string", enum: ["auto", "en", "zh"] },
1098
+ },
1099
+ required: ["samples"],
1100
+ },
1101
+ },
1102
+ {
1103
+ name: "dislop_model_score",
1104
+ description:
1105
+ "Run the bundled zero-dependency 15 KB Pocket ML ensemble (`pocket-slop-v1`) + 5-domain pack router on `text` to detect clean-wordlist stealth AI vapor paragraphs and explain top contributing signals (0 network calls).",
1106
+ inputSchema: {
1107
+ type: "object",
1108
+ properties: {
1109
+ text: { type: "string", description: "Draft text to score with bundled Pocket ML" },
1110
+ threshold: { type: "number", description: "Optional paragraph flag threshold (0..1)" },
1111
+ },
1112
+ required: ["text"],
1113
+ },
1114
+ },
1115
+ {
1116
+ name: "dislop_model_status",
1117
+ description:
1118
+ "Inspect bundled models, installed optional model weights, hardware memory budget, and recommended optional local model tier.",
1119
+ inputSchema: {
1120
+ type: "object",
1121
+ properties: {},
1122
+ },
1123
+ },
1124
+ ];
1125
+
1126
+ rl.on("line", (line) => {
1127
+ const trimmed = line.trim();
1128
+ if (!trimmed) return;
1129
+ let req;
1130
+ try {
1131
+ req = JSON.parse(trimmed);
1132
+ } catch {
1133
+ return;
1134
+ }
1135
+ const { id, method, params = {} } = req;
1136
+ if (id === undefined || id === null) return;
1137
+
1138
+ if (method === "initialize") {
1139
+ const clientVersion = params.protocolVersion || "2024-11-05";
1140
+ send({
1141
+ jsonrpc: "2.0",
1142
+ id,
1143
+ result: {
1144
+ protocolVersion: clientVersion,
1145
+ capabilities: { tools: {} },
1146
+ serverInfo: { name: "dislop", version: ENGINE_VERSION },
1147
+ },
1148
+ });
1149
+ return;
1150
+ }
1151
+
1152
+ if (method === "ping") {
1153
+ send({ jsonrpc: "2.0", id, result: {} });
1154
+ return;
1155
+ }
1156
+
1157
+ if (method === "tools/list") {
1158
+ send({ jsonrpc: "2.0", id, result: { tools } });
1159
+ return;
1160
+ }
1161
+
1162
+ if (method === "tools/call") {
1163
+ const name = params.name;
1164
+ const args = params.arguments || {};
1165
+ try {
1166
+ if (name === "dislop_packs") {
1167
+ const list = Object.values(packs).map((p) => ({
1168
+ id: p.id,
1169
+ tier: p.tier,
1170
+ name: p.name,
1171
+ modalities: p.modalities,
1172
+ ruleCount: (p.rules || []).length,
1173
+ summary: p.summary,
1174
+ }));
1175
+ toolResult(id, { packs: list });
1176
+ return;
1177
+ }
1178
+
1179
+ if (name === "dislop_catalog") {
1180
+ const result = queryCatalog(catalogEntries, {
1181
+ query: args.query || "",
1182
+ pack: args.pack || null,
1183
+ category: args.category || null,
1184
+ dimension: args.dimension || null,
1185
+ family: args.family || null,
1186
+ modality: args.modality || null,
1187
+ severity: args.severity || null,
1188
+ tier: args.tier || null,
1189
+ includeExemplars: args.includeExemplars !== false,
1190
+ limit: Number.isInteger(args.limit) && args.limit > 0 ? args.limit : null,
1191
+ });
1192
+ toolResult(id, result);
1193
+ return;
1194
+ }
1195
+
1196
+ if (name === "dislop_explain") {
1197
+ if (!args.ruleId) {
1198
+ toolResult(id, { error: "Missing required argument `ruleId`" }, true);
1199
+ return;
1200
+ }
1201
+ for (const p of Object.values(packs)) {
1202
+ const rule = (p.rules || []).find((r) => r.id === args.ruleId);
1203
+ if (rule) {
1204
+ toolResult(id, formatRuleForExplain(rule, p.id, args.lang));
1205
+ return;
1206
+ }
1207
+ }
1208
+ const pat = patternByRuleId && patternByRuleId[args.ruleId];
1209
+ if (pat) {
1210
+ const guards = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
1211
+ const synthRule = {
1212
+ id: args.ruleId,
1213
+ tier: "taste",
1214
+ severity: pat.severityDefault || "info",
1215
+ category: pat.category || "general",
1216
+ family: pat.dimension ? `${pat.dimension}/${args.ruleId}` : "pattern-bank",
1217
+ modalities: pat.modalities || ["markdown", "text"],
1218
+ tags: pat.tags || [],
1219
+ message: pat.mechanism || pat.name || { en: "", zh: "" },
1220
+ ...(guards ? { deletionTest: { en: guards, zh: guards } } : {}),
1221
+ ...(pat.exemplar ? { exemplar: pat.exemplar } : {}),
1222
+ };
1223
+ toolResult(id, formatRuleForExplain(synthRule, pat.packId || "pattern-bank", args.lang));
1224
+ return;
1225
+ }
1226
+ if (args.ruleId === "pocket-stealth-vapor") {
1227
+ toolResult(id, formatRuleForExplain(POCKET_STEALTH_VAPOR_RULE, "pocket-model", args.lang));
1228
+ return;
1229
+ }
1230
+ toolResult(id, { error: `Unknown ruleId '${args.ruleId}'` }, true);
1231
+ return;
1232
+ }
1233
+
1234
+ if (name === "dislop_check") {
1235
+ const hasText = typeof args.text === "string";
1236
+ const hasPath = typeof args.path === "string" && args.path.trim().length > 0;
1237
+ if (hasText === hasPath) {
1238
+ toolResult(
1239
+ id,
1240
+ { error: "Provide exactly one of `text` (in-memory string) or `path` (workspace file path)." },
1241
+ true
1242
+ );
1243
+ return;
1244
+ }
1245
+
1246
+ const liveConfig = loadConfig(cwd);
1247
+ const verbosity = args.verbosity === "full" ? "full" : "compact";
1248
+ const includeMl = Boolean(args.ml);
1249
+ const includePatterns = Boolean(args.patterns);
1250
+ const wantProfile = args.profile !== false;
1251
+ const banks = includePatterns ? loadPatternBanks() : null;
1252
+
1253
+ if (hasText) {
1254
+ const fn = args.filename || "draft.md";
1255
+ const mod = detectModality(fn) || "markdown";
1256
+ const effPack =
1257
+ args.pack === "auto" && (mod === "markdown" || mod === "text")
1258
+ ? predictPackWithPocketRouter(args.text).recommendedPack
1259
+ : args.pack === "auto"
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 });
1265
+ let findings = res.findings;
1266
+ if (includePatterns) {
1267
+ findings = mergePatternBankFindings(findings, auditPatterns(args.text, { filename: fn, modality: mod, banks }).findings);
1268
+ }
1269
+ if (includeMl && (mod === "markdown" || mod === "text")) {
1270
+ findings = [...findings, ...buildPocketMlFindings(args.text, fn, findings).findings];
1271
+ }
1272
+ const profile = wantProfile && (mod === "markdown" || mod === "text") ? analyzeTextProfile(args.text, { modality: mod }) : null;
1273
+ const formatted = formatFindingsForMcp(findings, verbosity, args.lang);
1274
+ toolResult(id, {
1275
+ pack: packId,
1276
+ modality: mod,
1277
+ checked: true,
1278
+ skipped: [],
1279
+ count: formatted.length,
1280
+ findings: formatted,
1281
+ ...(verbosity === "compact" && formatted.length > 0
1282
+ ? { explainHint: "Call dislop_explain(ruleId) for before/trap/after examples." }
1283
+ : {}),
1284
+ ...(profile ? { profile } : {}),
1285
+ });
1286
+ return;
1287
+ }
1288
+
1289
+ // Check lexical workspace containment BEFORE touching filesystem, then realpath containment against symlinks
1290
+ const realCwd = fs.realpathSync(cwd);
1291
+ const resolvedLex = path.resolve(realCwd, args.path);
1292
+ const lexRel = path.relative(realCwd, resolvedLex);
1293
+ if (lexRel === ".." || lexRel.startsWith(`..${path.sep}`) || path.isAbsolute(lexRel)) {
1294
+ toolResult(id, { error: "Path must stay within the current workspace directory." }, true);
1295
+ return;
1296
+ }
1297
+ if (!fs.existsSync(resolvedLex) || !fs.statSync(resolvedLex).isFile()) {
1298
+ toolResult(id, { error: `File not found: ${args.path}` }, true);
1299
+ return;
1300
+ }
1301
+ const realTarget = fs.realpathSync(resolvedLex);
1302
+ const rel = path.relative(realCwd, realTarget);
1303
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
1304
+ toolResult(id, { error: "Path must stay within the current workspace directory." }, true);
1305
+ return;
1306
+ }
1307
+ const mod = detectModality(realTarget);
1308
+ if (!mod) {
1309
+ toolResult(id, { error: `Unsupported file extension for '${args.path}'` }, true);
1310
+ return;
1311
+ }
1312
+ 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
+ const res = inspectSingleFile(
1326
+ { absPath: realTarget, rel: posixRel, modality: mod },
1327
+ packs,
1328
+ effPackArg,
1329
+ liveConfig,
1330
+ { includeMl, includePatterns, banks }
1331
+ );
1332
+ let profile = null;
1333
+ if (res.checked && wantProfile && rawTxtForPack !== null && (mod === "markdown" || mod === "text")) {
1334
+ profile = analyzeTextProfile(rawTxtForPack, { modality: mod });
1335
+ }
1336
+ const formatted = formatFindingsForMcp(res.findings, verbosity, args.lang);
1337
+ toolResult(id, {
1338
+ pack: pickPackForFile(posixRel, mod, effPackArg, liveConfig),
1339
+ modality: mod,
1340
+ checked: res.checked,
1341
+ skipped: res.skipped,
1342
+ count: formatted.length,
1343
+ findings: formatted,
1344
+ ...(verbosity === "compact" && formatted.length > 0
1345
+ ? { explainHint: "Call dislop_explain(ruleId) for before/trap/after examples." }
1346
+ : {}),
1347
+ ...(profile ? { profile } : {}),
1348
+ });
1349
+ return;
1350
+ }
1351
+
1352
+ if (name === "dislop_voice_extract_offline") {
1353
+ if (!Array.isArray(args.samples) || args.samples.length === 0) {
1354
+ toolResult(id, { error: "Non-empty `samples` string array is required." }, true);
1355
+ return;
1356
+ }
1357
+ if (args.samples.length > 15) {
1358
+ toolResult(id, { error: "Provide at most 15 sample passages per call." }, true);
1359
+ return;
1360
+ }
1361
+ if (args.samples.some((s) => typeof s !== "string")) {
1362
+ toolResult(id, { error: "Every element in `samples` must be a string." }, true);
1363
+ return;
1364
+ }
1365
+ const nonBlankSamples = args.samples.map((s) => s.trim()).filter(Boolean);
1366
+ if (nonBlankSamples.length === 0) {
1367
+ toolResult(id, { error: "At least one non-empty sample passage is required." }, true);
1368
+ return;
1369
+ }
1370
+ const voice = extractVoiceProfileOffline(nonBlankSamples, { lang: args.lang || "auto" });
1371
+ toolResult(id, voice);
1372
+ return;
1373
+ }
1374
+
1375
+ if (name === "dislop_model_score") {
1376
+ if (typeof args.text !== "string") {
1377
+ toolResult(id, { error: "Required string argument `text` missing." }, true);
1378
+ return;
1379
+ }
1380
+ if (args.threshold !== undefined && args.threshold !== null) {
1381
+ if (typeof args.threshold !== "number" || !Number.isFinite(args.threshold) || args.threshold < 0 || args.threshold > 1) {
1382
+ toolResult(id, { error: "`threshold` must be a number between 0 and 1." }, true);
1383
+ return;
1384
+ }
1385
+ }
1386
+ const thr = typeof args.threshold === "number" ? args.threshold : null;
1387
+ toolResult(id, analyzeDocumentWithPocketModels(args.text, { threshold: thr }));
1388
+ return;
1389
+ }
1390
+
1391
+ if (name === "dislop_model_status") {
1392
+ let rulesCount = 0;
1393
+ for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
1394
+ buildModelStatusReport({
1395
+ packsCount: Object.keys(packs).length,
1396
+ rulesCount,
1397
+ probeLoopback: false,
1398
+ })
1399
+ .then((st) => toolResult(id, st))
1400
+ .catch((e) => toolResult(id, { error: e.message }, true));
1401
+ return;
1402
+ }
1403
+
1404
+ toolResult(id, { error: `Unknown tool '${name}'` }, true);
1405
+ } catch (err) {
1406
+ toolResult(id, { error: err.message }, true);
1407
+ }
1408
+ return;
1409
+ }
1410
+
1411
+ send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });
1412
+ });
1413
+ }
1414
+
1415
+ function runResources(rest, packs) {
1416
+ const { flags } = parseFlags(rest);
1417
+ const format = flags.json ? "json" : flags.format || "text";
1418
+ assertTextOrJsonFormat(format);
1419
+ const asJson = format === "json";
1420
+ const payload = {
1421
+ schema: "dislop.resources/1",
1422
+ offlineCheck: true,
1423
+ note: "'dislop check' runs 100% locally with zero network requests and zero file uploads.",
1424
+ bundledPacks: Object.keys(packs).sort(),
1425
+ staticResources: {
1426
+ llmsIndex: "https://dislop.com/llms.txt",
1427
+ catalog: "https://dislop.com/catalog.json",
1428
+ awesomeIndex: "https://dislop.com/awesome/index.json",
1429
+ tasks: [
1430
+ "https://dislop.com/tasks/business-doc.md",
1431
+ "https://dislop.com/tasks/web-and-deck.md",
1432
+ "https://dislop.com/tasks/editorial-writing.md",
1433
+ "https://dislop.com/tasks/pre-release-gate.md",
1434
+ ],
1435
+ ruleTemplate: "https://dislop.com/rules/<rule-id>.md",
1436
+ },
1437
+ optionalCloudMcp: {
1438
+ url: "https://dislop.com/mcp",
1439
+ pricingAndFreeToken: "https://dislop.com/#pricing",
1440
+ tools: ["dislop_review", "dislop_deslop", "dislop_voice_extract"],
1441
+ },
1442
+ };
1443
+ if (asJson) {
1444
+ console.log(JSON.stringify(payload, null, 2));
1445
+ return;
1446
+ }
1447
+ console.log(`dislop v${ENGINE_VERSION} resources (dislop check makes 0 network requests)`);
1448
+ console.log(`\nBundled offline packs: ${payload.bundledPacks.join(", ")}`);
1449
+ console.log(`\nFree read-only static resources (dislop.com):`);
1450
+ console.log(` - Agent index : ${payload.staticResources.llmsIndex}`);
1451
+ console.log(` - Full catalog: ${payload.staticResources.catalog}`);
1452
+ console.log(` - Awesome 87 : ${payload.staticResources.awesomeIndex}`);
1453
+ console.log(` - Rule card : ${payload.staticResources.ruleTemplate}`);
1454
+ console.log(`\nOptional hosted Cloud Remote MCP (login + 30 free credits/mo):`);
1455
+ console.log(` - Endpoint : ${payload.optionalCloudMcp.url}`);
1456
+ console.log(` - Free token : ${payload.optionalCloudMcp.pricingAndFreeToken}`);
1457
+ }
1458
+
1459
+ function loadPatternBanks(customPatternsDir = PATTERNS_DIR) {
1460
+ const bankDir = path.join(customPatternsDir, "banks");
1461
+ const out = {};
1462
+ if (!fs.existsSync(bankDir)) return out;
1463
+ for (const entry of fs.readdirSync(bankDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1464
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
1465
+ const data = JSON.parse(fs.readFileSync(path.join(bankDir, entry.name), "utf8"));
1466
+ out[data.id || entry.name.replace(/\.json$/, "")] = data;
1467
+ }
1468
+ return out;
1469
+ }
1470
+
1471
+ function runPatterns(args) {
1472
+ const { flags, positional } = parseFlags(args);
1473
+ const format = flags.json ? "json" : flags.format || "text";
1474
+ assertTextOrJsonFormat(format);
1475
+ const lang = flags.lang || "en";
1476
+ const banks = loadPatternBanks();
1477
+ const angles = flags.angle ? String(flags.angle).split(",").map((s) => s.trim()).filter(Boolean) : null;
1478
+
1479
+ let text = "";
1480
+ let filename = flags["stdin-filename"] || "stdin.md";
1481
+ let modality = detectModality(filename) || "markdown";
1482
+ let ooxml = null;
1483
+
1484
+ if (positional.length === 0 || positional[0] === "-") {
1485
+ text = fs.readFileSync(0, "utf8");
1486
+ } else {
1487
+ const abs = path.resolve(process.cwd(), positional[0]);
1488
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
1489
+ console.error(`dislop: file not found: ${positional[0]}`);
1490
+ process.exit(2);
1491
+ }
1492
+ filename = positional[0];
1493
+ const detected = detectModality(abs);
1494
+ if (!detected) {
1495
+ console.error(`dislop: unsupported file extension for '${positional[0]}'`);
1496
+ process.exit(2);
1497
+ }
1498
+ modality = detected;
1499
+ const buf = fs.readFileSync(abs);
1500
+ try {
1501
+ if (modality === "pptx" || modality === "docx") {
1502
+ ooxml = readZipXmlEntries(buf);
1503
+ } else {
1504
+ text = decodeUtf8Strict(buf);
1505
+ }
1506
+ } catch (err) {
1507
+ console.error(`dislop: uninspectable ${modality.toUpperCase()} file '${positional[0]}': ${err.message}`);
1508
+ process.exit(2);
1509
+ }
1510
+ }
1511
+
1512
+ const profile = analyzePatternProfile(text, { filename, modality, banks, angles, ooxml });
1513
+ if (format === "json") {
1514
+ console.log(JSON.stringify(profile, null, 2));
1515
+ return;
1516
+ }
1517
+ if (profile.findingCount === 0) {
1518
+ console.log(`dislop patterns: ok (${filename}, 0 pattern findings)`);
1519
+ return;
1520
+ }
1521
+ console.log(`dislop patterns: ${profile.findingCount} finding(s) in ${filename} (dimensions: ${profile.activeDimensions.join(", ")})`);
1522
+ for (const f of profile.findings) {
1523
+ const msg = f.message?.[lang] || f.message?.en || "";
1524
+ console.log(` [${f.severity.toUpperCase()}] ${f.file}:${f.location} ${f.ruleId} (${f.detectionAngle}${f.metric ? ` · ${f.metric}` : ""})`);
1525
+ console.log(` match: "${f.match}"`);
1526
+ console.log(` why: ${msg}`);
1527
+ }
1528
+ }
1529
+
1530
+ function runVoice(args) {
1531
+ const { flags, positional } = parseFlags(args);
1532
+ const format = flags.json ? "json" : flags.format || "text";
1533
+ assertTextOrJsonFormat(format);
1534
+ const lang = flags.lang || "auto";
1535
+ const samples = [];
1536
+
1537
+ if (positional.length === 0 || positional[0] === "-") {
1538
+ const raw = fs.readFileSync(0, "utf8");
1539
+ samples.push(...raw.split(/\n\s*\n/).map((s) => s.trim()).filter(Boolean));
1540
+ } else {
1541
+ for (const p of positional) {
1542
+ const abs = path.resolve(process.cwd(), p);
1543
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
1544
+ console.error(`dislop: file not found: ${p}`);
1545
+ process.exit(2);
1546
+ }
1547
+ samples.push(decodeUtf8Strict(fs.readFileSync(abs)));
1548
+ }
1549
+ }
1550
+ if (samples.length === 0) {
1551
+ console.error("dislop voice: provide at least one non-empty sample file or stdin text");
1552
+ process.exit(2);
1553
+ }
1554
+
1555
+ const result = extractVoiceProfileOffline(samples, { lang });
1556
+ if (flags.output) {
1557
+ const outAbs = path.resolve(process.cwd(), String(flags.output));
1558
+ fs.mkdirSync(path.dirname(outAbs), { recursive: true });
1559
+ fs.writeFileSync(outAbs, JSON.stringify(result, null, 2) + "\n", "utf8");
1560
+ }
1561
+ if (flags.json || flags.format === "json") {
1562
+ console.log(JSON.stringify(result, null, 2));
1563
+ return;
1564
+ }
1565
+ const s = result.stylometrics;
1566
+ console.log(`dislop voice (${result.mode}, 0 network calls)`);
1567
+ console.log(` samples=${s.sampleCount} · sentences=${s.sentenceCount} · mean=${s.meanLength} · cv=${s.lengthCV} · band=[${s.targetLengthBand.join(", ")}]`);
1568
+ console.log(` tone: ${result.profile.tone}`);
1569
+ for (const h of result.profile.sentenceHabits) {
1570
+ console.log(` - ${h}`);
1571
+ }
1572
+ }
1573
+
1574
+ async function promptInteractiveTier(defaultTier, lang) {
1575
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1576
+ const q =
1577
+ lang === "zh"
1578
+ ? `\n请选择要选装的本地模型档位 [none / fast / balanced / quality](回车默认 ${defaultTier}):`
1579
+ : `\nChoose optional local model tier [none / fast / balanced / quality] (Enter for '${defaultTier}'): `;
1580
+ return new Promise((resolve) => {
1581
+ rl.question(q, (ans) => {
1582
+ rl.close();
1583
+ const val = String(ans || "").trim().toLowerCase();
1584
+ resolve(val || defaultTier);
1585
+ });
1586
+ });
1587
+ }
1588
+
1589
+ async function runLocalDeslopCli(target, flags, packs) {
1590
+ const lang = flags.lang || "en";
1591
+ let rawText = "";
1592
+ let filename = flags["stdin-filename"] || "draft.md";
1593
+ if (!target || target === "-") {
1594
+ rawText = fs.readFileSync(0, "utf8");
1595
+ } else {
1596
+ const abs = path.resolve(process.cwd(), target);
1597
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
1598
+ console.error(`dislop: file not found: ${target}`);
1599
+ process.exit(2);
1600
+ }
1601
+ filename = path.basename(abs);
1602
+ rawText = decodeUtf8Strict(fs.readFileSync(abs));
1603
+ }
1604
+ const modality = detectModality(filename) || "markdown";
1605
+ const config = loadConfig(process.cwd(), flags.config || null);
1606
+ const explicitPack =
1607
+ flags.pack === "auto"
1608
+ ? predictPackWithPocketRouter(rawText).recommendedPack
1609
+ : flags.pack || null;
1610
+ const packId = pickPackForFile(filename, modality, explicitPack, config);
1611
+ const pack = resolveEffectivePack(packId, packs, config);
1612
+
1613
+ let res;
1614
+ try {
1615
+ res = await runLocalDeslop({
1616
+ text: rawText,
1617
+ pack,
1618
+ modality,
1619
+ endpoint: flags.endpoint || null,
1620
+ model: flags.model || null,
1621
+ allowLan: Boolean(flags["allow-lan"]),
1622
+ });
1623
+ } catch (err) {
1624
+ console.error(`dislop: ${err.message}`);
1625
+ process.exit(2);
1626
+ }
1627
+
1628
+ if (!res.ok) {
1629
+ if (flags.json || flags.format === "json") {
1630
+ console.log(JSON.stringify(res, null, 2));
1631
+ } else {
1632
+ console.error(`dislop: ${res.error}`);
1633
+ }
1634
+ process.exit(2);
1635
+ }
1636
+
1637
+ if (flags.output) {
1638
+ const outAbs = path.resolve(process.cwd(), String(flags.output));
1639
+ fs.mkdirSync(path.dirname(outAbs), { recursive: true });
1640
+ fs.writeFileSync(outAbs, res.text, "utf8");
1641
+ }
1642
+
1643
+ if (flags.json || flags.format === "json") {
1644
+ console.log(JSON.stringify(res, null, 2));
1645
+ return;
1646
+ }
1647
+
1648
+ if (!flags.output) {
1649
+ process.stdout.write(res.text.endsWith("\n") ? res.text : res.text + "\n");
1650
+ } else if (lang === "zh") {
1651
+ console.log(
1652
+ `dislop 本地改写完成(${res.model}):改写 ${res.rewrittenParagraphs} 段,保留原段 ${res.keptOriginalParagraphs} 段,事实核验 ${res.factLedgerOk ? "通过" : "未通过"} -> ${flags.output}`
1653
+ );
1654
+ } else {
1655
+ console.log(
1656
+ `dislop local deslop (${res.model}): rewrote ${res.rewrittenParagraphs} paragraph(s), kept ${res.keptOriginalParagraphs} untouched, fact ledger ${res.factLedgerOk ? "ok" : "drifted"} -> ${flags.output}`
1657
+ );
1658
+ }
1659
+ }
1660
+
1661
+ async function runModel(args, packs) {
1662
+ const { flags, positional } = parseFlags(args);
1663
+ const action = positional[0] || "status";
1664
+ const validActions = new Set(["status", "recommend", "score", "install", "setup", "import", "remove", "rm", "deslop"]);
1665
+ if (!validActions.has(action)) {
1666
+ console.error(
1667
+ `dislop model: unknown action '${action}' (expected status, recommend, score, install, setup, import, remove, or deslop)`
1668
+ );
1669
+ process.exit(2);
1670
+ }
1671
+ const restPos = positional.slice(1);
1672
+ const lang = flags.lang || "en";
1673
+ const asJson = Boolean(flags.json || flags.format === "json");
1674
+
1675
+ if (action === "score") {
1676
+ const target = restPos[0] || "-";
1677
+ let threshold = null;
1678
+ if (flags.threshold !== undefined) {
1679
+ threshold = Number(flags.threshold);
1680
+ if (typeof flags.threshold === "boolean" || String(flags.threshold).trim() === "" || !Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
1681
+ console.error(`dislop model score: invalid --threshold '${flags.threshold}' (expected a number between 0 and 1)`);
1682
+ process.exit(2);
1683
+ }
1684
+ }
1685
+ let rawText = "";
1686
+ let label = flags["stdin-filename"] || "stdin.md";
1687
+ if (target === "-") {
1688
+ rawText = fs.readFileSync(0, "utf8");
1689
+ } else {
1690
+ const abs = path.resolve(process.cwd(), target);
1691
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
1692
+ console.error(`dislop model score: file not found: ${target}`);
1693
+ process.exit(2);
1694
+ }
1695
+ label = target;
1696
+ rawText = decodeUtf8Strict(fs.readFileSync(abs));
1697
+ }
1698
+ const result = analyzeDocumentWithPocketModels(rawText, { threshold });
1699
+ if (asJson) {
1700
+ console.log(JSON.stringify({ file: label, ...result }, null, 2));
1701
+ return;
1702
+ }
1703
+ const pct = Math.round(result.documentProbability * 100);
1704
+ if (lang === "zh") {
1705
+ console.log(`dislop 内置传统模型评分(pocket-slop-v1 · 0 联网):${label}`);
1706
+ console.log(
1707
+ ` 文档最高温吞水概率 : ${pct}%(阈值 ${Math.round(result.threshold * 100)}% · 命中段落 ${result.flaggedCount}/${result.paragraphs.length})`
1708
+ );
1709
+ console.log(
1710
+ ` 自动判别场景包 : ${result.packRouter.recommendedPack}(置信度 ${Math.round(result.packRouter.confidence * 100)}%)`
1711
+ );
1712
+ for (const p of result.paragraphs) {
1713
+ const mark = p.flagged ? "[提醒]" : "[正常]";
1714
+ const drv = p.topDrivers.map((d) => d.reason.zh).join("、");
1715
+ console.log(` ${mark} 第 ${p.startLine}-${p.endLine} 行 (${Math.round(p.slopProbability * 100)}%)${drv ? `:${drv}` : ""}`);
1716
+ }
1717
+ } else {
1718
+ console.log(`dislop bundled Pocket ML score (pocket-slop-v1 · 0 network calls): ${label}`);
1719
+ console.log(
1720
+ ` Max paragraph slop : ${pct}% (threshold ${Math.round(result.threshold * 100)}% · flagged ${result.flaggedCount}/${result.paragraphs.length})`
1721
+ );
1722
+ console.log(
1723
+ ` Recommended pack : ${result.packRouter.recommendedPack} (confidence ${Math.round(result.packRouter.confidence * 100)}%)`
1724
+ );
1725
+ for (const p of result.paragraphs) {
1726
+ const mark = p.flagged ? "[FLAG]" : "[OK] ";
1727
+ const drv = p.topDrivers.map((d) => d.reason.en).join("; ");
1728
+ console.log(` ${mark} lines ${p.startLine}-${p.endLine} (${Math.round(p.slopProbability * 100)}%)${drv ? ` — ${drv}` : ""}`);
1729
+ }
1730
+ }
1731
+ return;
1732
+ }
1733
+
1734
+ if ( action === "install" || action === "setup" ) {
1735
+ let rulesCount = 0;
1736
+ for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
1737
+ const status = await buildModelStatusReport({
1738
+ packsCount: Object.keys(packs).length,
1739
+ rulesCount,
1740
+ probeLoopback: false,
1741
+ cacheDir: flags["cache-dir"] || null,
1742
+ });
1743
+ let chosenTier = flags.tier || null;
1744
+ if (!chosenTier) {
1745
+ if (action === "setup" && process.stdin.isTTY && !flags.yes && !asJson && !flags["dry-run"]) {
1746
+ if (lang === "zh") {
1747
+ console.log(`dislop 模型选装向导(内置 15 KB 传统集成模型已就绪)`);
1748
+ console.log(` 硬件检测:${status.hardware.platform}/${status.hardware.arch} · ${status.hardware.totalMemoryGb} GB 内存 · 推荐档位 ${status.recommendation.tier}`);
1749
+ for (const t of Object.values(LOCAL_MODEL_TIERS)) {
1750
+ console.log(` - ${t.tier.padEnd(9)} (${String(t.approxDownloadMb).padStart(4)} MB): ${t.summary.zh}`);
1751
+ }
1752
+ } else {
1753
+ console.log(`dislop optional model setup (bundled 15 KB Pocket ML is already active)`);
1754
+ console.log(` Hardware: ${status.hardware.platform}/${status.hardware.arch} · ${status.hardware.totalMemoryGb} GB RAM · recommended '${status.recommendation.tier}'`);
1755
+ for (const t of Object.values(LOCAL_MODEL_TIERS)) {
1756
+ console.log(` - ${t.tier.padEnd(9)} (${String(t.approxDownloadMb).padStart(4)} MB): ${t.summary.en}`);
1757
+ }
1758
+ }
1759
+ chosenTier = await promptInteractiveTier(status.recommendation.tier, lang);
1760
+ } else {
1761
+ chosenTier = restPos[0] || "auto";
1762
+ }
1763
+ }
1764
+
1765
+ const res = installOptionalModel({
1766
+ tier: chosenTier,
1767
+ provider: flags.provider || "ollama",
1768
+ force: Boolean(flags.force),
1769
+ dryRun: Boolean(flags["dry-run"]),
1770
+ cacheDir: flags["cache-dir"] || null,
1771
+ });
1772
+
1773
+ if (asJson) {
1774
+ console.log(JSON.stringify(res, null, 2));
1775
+ if (!res.ok) process.exit(res.blockedByHardware ? 1 : 2);
1776
+ return;
1777
+ }
1778
+
1779
+ if (!res.ok) {
1780
+ const msg = res.warning?.[lang] || res.message?.[lang] || res.warning?.en || res.message?.en || res.error;
1781
+ console.error(`dislop model install: ${msg}`);
1782
+ process.exit(res.blockedByHardware ? 1 : 2);
1783
+ }
1784
+ if (res.dryRun) {
1785
+ console.log(
1786
+ lang === "zh"
1787
+ ? `dislop 选装预检通过:档位 ${res.tier} (${res.modelId || res.provider}, 约 ${res.approxDownloadMb || 0} MB) -> ${res.command || res.modelCacheDir}`
1788
+ : `dislop install dry-run passed: tier '${res.tier}' (${res.modelId || res.provider}, ~${res.approxDownloadMb || 0} MB) -> ${res.command || res.modelCacheDir}`
1789
+ );
1790
+ return;
1791
+ }
1792
+ const doneMsg = res.message?.[lang] || res.message?.en || `Installed tier '${res.tier}' (${res.modelId}).`;
1793
+ console.log(doneMsg);
1794
+ return;
1795
+ }
1796
+
1797
+ if (action === "import") {
1798
+ const fileArg = restPos[0];
1799
+ if (!fileArg) {
1800
+ console.error("Usage: dislop model import <file.gguf|file.onnx> [--tier <tier>] [--sha256 <hex>] [--no-copy] [--json]");
1801
+ process.exit(2);
1802
+ }
1803
+ const res = importLocalModelFile({
1804
+ filePath: fileArg,
1805
+ tier: flags.tier || "custom",
1806
+ expectedSha256: flags.sha256 || null,
1807
+ copyFile: !flags["no-copy"],
1808
+ cacheDir: flags["cache-dir"] || null,
1809
+ });
1810
+ if (asJson) {
1811
+ console.log(JSON.stringify(res, null, 2));
1812
+ if (!res.ok) process.exit(2);
1813
+ return;
1814
+ }
1815
+ if (!res.ok) {
1816
+ console.error(`dislop model import: ${res.error}`);
1817
+ process.exit(2);
1818
+ }
1819
+ console.log(`Imported ${res.imported.id} (tier=${res.imported.tier}, sha256=${res.imported.sha256.slice(0, 12)}…) -> ${res.imported.path}`);
1820
+ return;
1821
+ }
1822
+
1823
+ if (action === "remove" || action === "rm") {
1824
+ const target = restPos[0] || flags.tier;
1825
+ const res = removeInstalledModel({ target, cacheDir: flags["cache-dir"] || null });
1826
+ if (asJson) {
1827
+ console.log(JSON.stringify(res, null, 2));
1828
+ if (!res.ok) process.exit(1);
1829
+ return;
1830
+ }
1831
+ if (!res.ok) {
1832
+ console.error(`dislop model remove: ${res.error || `no cached model matched '${target}'`}`);
1833
+ process.exit(1);
1834
+ }
1835
+ console.log(`Removed ${res.removedCount} cached model entry(s).`);
1836
+ return;
1837
+ }
1838
+
1839
+ if (action === "deslop") {
1840
+ await runLocalDeslopCli(restPos[0] || "-", flags, packs);
1841
+ return;
1842
+ }
1843
+
1844
+ let rulesCount = 0;
1845
+ for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
1846
+ const report = await buildModelStatusReport({
1847
+ packsCount: Object.keys(packs).length,
1848
+ rulesCount,
1849
+ probeLoopback: !flags["no-loopback"],
1850
+ cacheDir: flags["cache-dir"] || null,
1851
+ });
1852
+
1853
+ if (asJson) {
1854
+ console.log(JSON.stringify(report, null, 2));
1855
+ return;
1856
+ }
1857
+
1858
+ const hw = report.hardware;
1859
+ const rec = report.recommendation;
1860
+ const bm = report.bundledModels?.[0];
1861
+ if (lang === "zh") {
1862
+ console.log(`dislop 本地引擎、随包传统模型与选装小模型状态(检查全程 0 联网)`);
1863
+ console.log(` 内置确定性引擎 : 已就绪(${report.builtinDeterministic.bundledPacks} 套规则包 / ${report.builtinDeterministic.bundledRules} 条规则全量内置)`);
1864
+ if (bm) {
1865
+ console.log(` 随包传统模型 : 已内置 ${bm.id}(约 ${bm.approxGzipKb} KB gz · 含隐蔽水文集成评分与场景自动路由)`);
1866
+ }
1867
+ console.log(` 当前机器硬件 : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB 内存${hw.freeDiskGb !== null ? ` · 剩余磁盘 ${hw.freeDiskGb} GB` : ""}`);
1868
+ console.log(` 可选生成小模型 : ${rec.tier}${rec.modelId ? ` (${rec.modelId}, 约 ${rec.approxDownloadMb} MB)` : "(无需额外下载)"}`);
1869
+ console.log(` 说明 : ${rec.reason.zh}`);
1870
+ if (rec.installHint) console.log(` 按需选装命令 : ${rec.installHint}`);
1871
+ if (report.installedModels.length > 0) {
1872
+ console.log(` 已装本地权重 : ${report.installedModels.map((m) => `${m.id}[${m.tier}]`).join(", ")}`);
1873
+ }
1874
+ if (report.localRunners.length > 0) {
1875
+ for (const r of report.localRunners) {
1876
+ console.log(` 已发现本地服务 : ${r.kind} (${r.endpoint}) -> ${r.models.join(", ") || "无已装模型"}`);
1877
+ }
1878
+ }
1879
+ } else {
1880
+ console.log(`dislop local engine, bundled ML & optional model status (0 external network calls)`);
1881
+ console.log(` Built-in engine : ready (${report.builtinDeterministic.bundledPacks} packs / ${report.builtinDeterministic.bundledRules} rules bundled offline)`);
1882
+ if (bm) {
1883
+ console.log(` Bundled ML : ready (${bm.id}, ~${bm.approxGzipKb} KB gz · paragraph slop ensemble + domain router)`);
1884
+ }
1885
+ console.log(` Hardware : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB RAM${hw.freeDiskGb !== null ? ` · ${hw.freeDiskGb} GB free disk` : ""}`);
1886
+ console.log(` Recommended SLM : ${rec.tier}${rec.modelId ? ` (${rec.modelId}, ~${rec.approxDownloadMb} MB)` : " (no extra download needed)"}`);
1887
+ console.log(` Reason : ${rec.reason.en}`);
1888
+ if (rec.installHint) console.log(` Optional install: ${rec.installHint}`);
1889
+ if (report.installedModels.length > 0) {
1890
+ console.log(` Cached weights : ${report.installedModels.map((m) => `${m.id}[${m.tier}]`).join(", ")}`);
1891
+ }
1892
+ if (report.localRunners.length > 0) {
1893
+ for (const r of report.localRunners) {
1894
+ console.log(` Active loopback : ${r.kind} (${r.endpoint}) -> ${r.models.join(", ") || "no models loaded"}`);
1895
+ }
1896
+ }
1897
+ }
1898
+ }
1899
+
1900
+ function printHelp() {
1901
+ console.log(`dislop v${ENGINE_VERSION} — Local linter for AI-written docs, slides, and web pages
1902
+
1903
+ Usage:
1904
+ dislop check [paths... | -] [--pack <id|auto>] [--ml] [--patterns] [--fail-on error|warning|info|never]
1905
+ [--format text|json|sarif|github|md] [--profile] [--changed [ref] | --staged]
1906
+ [--stdin-filename <name>] [--report-unused] [--lang en|zh]
1907
+ dislop voice [paths... | -] [--output|-o <voice.json>] [--lang auto|en|zh] [--json]
1908
+ dislop model [status|score|install|import|remove|deslop] [target] [--tier <t>] [--lang en|zh] [--json]
1909
+ dislop setup [--tier auto|none|fast|balanced|quality] [--dry-run] [--force] [--lang en|zh]
1910
+ dislop deslop [file | -] --local [--endpoint <url>] [--model <id>] [--output|-o <file>] [--json]
1911
+ dislop explain <rule-id> [--lang en|zh] [--json]
1912
+ dislop catalog [query] [--pack <id>] [--category <cat>] [--dimension <dim>]
1913
+ [--family <prefix>] [--modality <mod>] [--severity <sev>] [--tier invariant|taste]
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`);
1921
+ }
1922
+
1923
+ async function main() {
1924
+ const argv = process.argv.slice(2);
1925
+ const packs = loadAllPacks();
1926
+ const patternByRuleId = loadPatternLibrary();
1927
+
1928
+ if (argv.includes("--mcp")) {
1929
+ runMcpServer(packs, patternByRuleId);
1930
+ return;
1931
+ }
1932
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help" || argv[0] === "help") {
1933
+ printHelp();
1934
+ return;
1935
+ }
1936
+ if (argv[0] === "-v" || argv[0] === "--version") {
1937
+ console.log(ENGINE_VERSION);
1938
+ return;
1939
+ }
1940
+
1941
+ const cmd = argv[0];
1942
+ const rest = argv.slice(1);
1943
+ if (cmd === "check") return runCheck(rest, packs);
1944
+ if (cmd === "voice") return runVoice(rest);
1945
+ if (cmd === "model" || cmd === "doctor") return await runModel(rest, packs);
1946
+ if (cmd === "setup") return await runModel(["setup", ...rest], packs);
1947
+ if (cmd === "deslop") {
1948
+ const { flags, positional } = parseFlags(rest);
1949
+ if (!flags.local) {
1950
+ console.error("dislop deslop: pass --local to run with a loopback local small model (0 external upload).");
1951
+ process.exit(2);
1952
+ }
1953
+ return await runLocalDeslopCli(positional[0] || "-", flags, packs);
1954
+ }
1955
+ if (cmd === "explain") return runExplain(rest, packs, patternByRuleId);
1956
+ if (cmd === "catalog" || cmd === "search") return runCatalog(rest, packs, patternByRuleId);
1957
+ if (cmd === "patterns") return runPatterns(rest);
1958
+ if (cmd === "packs") return runPacks(rest, packs);
1959
+ if (cmd === "resources") return runResources(rest, packs);
1960
+ if (cmd === "pack-test") return runPackTest(packs);
1961
+ if (cmd === "init") return runInit();
1962
+
1963
+ console.error(`dislop: unknown command '${cmd}'. Run 'dislop --help' for usage.`);
1964
+ process.exit(2);
1965
+ }
1966
+
1967
+ main();