dislop 0.9.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +7 -8
- package/.cursor-plugin/plugin.json +2 -3
- package/.pre-commit-hooks.yaml +5 -12
- package/PRODUCT.md +19 -63
- package/README.md +360 -252
- package/README.zh-CN.md +390 -240
- package/action.yml +30 -39
- package/bin/dislop-mcp.mjs +3 -4
- package/bin/dislop.mjs +4 -4594
- package/gemini-extension.json +2 -2
- package/llms-install.md +68 -0
- package/package.json +17 -63
- package/packs/common/artifact-qa/pack.json +5 -0
- package/packs/common/artifact-qa/prompts/rules.md +11 -0
- package/packs/common/artifact-qa/scripts/index.mjs +173 -0
- package/packs/common/slide-deck/pack.json +6 -0
- package/packs/common/slide-deck/prompts/rules.md +11 -0
- package/packs/common/slide-deck/scripts/index.mjs +62 -0
- package/packs/common/web-ui/pack.json +6 -0
- package/packs/common/web-ui/prompts/rules.md +11 -0
- package/packs/common/web-ui/scripts/index.mjs +80 -0
- package/packs/en/artifact-qa/pack.json +6 -0
- package/packs/en/artifact-qa/prompts/rules.md +14 -0
- package/packs/en/artifact-qa/scripts/index.mjs +90 -0
- package/packs/en/prose/pack.json +7 -0
- package/packs/en/prose/prompts/rules.md +26 -0
- package/packs/en/prose/scripts/index.mjs +290 -0
- package/packs/en/slide-deck/pack.json +7 -0
- package/packs/en/slide-deck/prompts/rules.md +17 -0
- package/packs/en/slide-deck/scripts/index.mjs +81 -0
- package/packs/en/web-ui/pack.json +7 -0
- package/packs/en/web-ui/prompts/rules.md +20 -0
- package/packs/en/web-ui/scripts/index.mjs +103 -0
- package/packs/zh/artifact-qa/pack.json +6 -0
- package/packs/zh/artifact-qa/prompts/rules.md +14 -0
- package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
- package/packs/zh/prose/pack.json +7 -0
- package/packs/zh/prose/prompts/rules.md +26 -0
- package/packs/zh/prose/scripts/index.mjs +305 -0
- package/packs/zh/slide-deck/pack.json +7 -0
- package/packs/zh/slide-deck/prompts/rules.md +17 -0
- package/packs/zh/slide-deck/scripts/index.mjs +75 -0
- package/packs/zh/web-ui/pack.json +7 -0
- package/packs/zh/web-ui/prompts/rules.md +20 -0
- package/packs/zh/web-ui/scripts/index.mjs +98 -0
- package/plugin.json +5 -6
- package/server.json +2 -2
- package/skills/deslop-docs/SKILL.md +10 -8
- package/skills/deslop-slides-docx/SKILL.md +7 -8
- package/skills/deslop-verify/SKILL.md +7 -8
- package/skills/deslop-web-ui/SKILL.md +7 -8
- package/skills/dislop/SKILL.md +16 -28
- package/skills/dislop/references/essay.md +1 -1
- package/skills/dislop/references/essay.zh-CN.md +1 -1
- package/skills/dislop/references/office.md +1 -1
- package/skills/dislop/references/office.zh-CN.md +1 -1
- package/skills/dislop/references/web-ui.md +1 -1
- package/skills/dislop/references/web-ui.zh-CN.md +1 -1
- package/skills/dislop/references/work-docs.md +1 -1
- package/skills/dislop/references/work-docs.zh-CN.md +1 -1
- package/src/cli-main.mjs +210 -0
- package/src/commands/check-fix.mjs +169 -0
- package/src/commands/doctor.mjs +110 -0
- package/src/commands/init.mjs +49 -0
- package/src/commands/login.mjs +82 -0
- package/src/commands/model.mjs +130 -0
- package/src/commands/packs.mjs +44 -0
- package/src/commands/verify.mjs +133 -0
- package/src/commands/voice.mjs +84 -0
- package/src/kernel/config.mjs +232 -0
- package/src/kernel/document-model.mjs +1412 -0
- package/src/kernel/fact-gate.mjs +615 -0
- package/src/kernel/file-discovery.mjs +139 -0
- package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
- package/src/kernel/pack-loader.mjs +715 -0
- package/src/kernel/patcher.mjs +341 -0
- package/src/kernel/pipeline.mjs +267 -0
- package/src/kernel/prompt-assembler.mjs +307 -0
- package/src/kernel/voice-profile.mjs +177 -0
- package/src/mcp/stdio-server.mjs +372 -0
- package/src/runners/auto-fix.mjs +59 -0
- package/src/runners/interactive-tty.mjs +461 -0
- package/src/runners/reporters.mjs +256 -0
- package/src/runtime/chunker.mjs +87 -0
- package/src/runtime/json-extract.mjs +144 -0
- package/src/runtime/privacy-gate.mjs +97 -0
- package/src/runtime/providers/anthropic.mjs +65 -0
- package/src/runtime/providers/cloud.mjs +136 -0
- package/src/runtime/providers/gemini.mjs +91 -0
- package/src/runtime/providers/local-model.mjs +139 -0
- package/src/runtime/providers/openai-compat.mjs +130 -0
- package/src/runtime/router.mjs +315 -0
- package/src/sdk/index.mjs +137 -0
- package/models/manifest.json +0 -90
- package/models/pocket-slop-v1.json +0 -1
- package/packs/business-brief/pack.json +0 -937
- package/packs/core/pack.json +0 -209
- package/packs/deck-and-ui/pack.json +0 -539
- package/packs/engineering-spec/pack.json +0 -144
- package/packs/executive-deck/pack.json +0 -98
- package/packs/literary-essay/pack.json +0 -344
- package/packs/regulated-comms/pack.json +0 -99
- package/patterns/ai-tic-rubric.json +0 -252
- package/patterns/banks/composite-fusion.json +0 -48
- package/patterns/banks/discourse-rhythm.json +0 -95
- package/patterns/banks/lexical-signals.json +0 -92
- package/patterns/banks/syntactic-frames.json +0 -52
- package/patterns/banks/visual-deck.json +0 -44
- package/patterns/dimensions/artifacts.json +0 -121
- package/patterns/dimensions/discourse.json +0 -438
- package/patterns/dimensions/lexical.json +0 -198
- package/patterns/dimensions/rhythm.json +0 -258
- package/patterns/dimensions/syntactic.json +0 -285
- package/patterns/dimensions/visual-and-deck.json +0 -530
- package/patterns/taxonomy.json +0 -112
- package/src/core.mjs +0 -5497
- package/src/dislop/review-picker.vim +0 -114
- package/src/local-model.mjs +0 -997
- package/src/pattern-engine.mjs +0 -1003
- package/src/pocket-model.mjs +0 -729
- package/src/review-apply.mjs +0 -151
- package/src/review-client.mjs +0 -1073
package/bin/dislop.mjs
CHANGED
|
@@ -1,4597 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
import os from "node:os";
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
import readline from "node:readline";
|
|
6
|
-
import { execFileSync, spawnSync } from "node:child_process";
|
|
7
|
-
import { fileURLToPath } from "node:url";
|
|
8
|
-
import {
|
|
9
|
-
ENGINE_VERSION,
|
|
10
|
-
SEVERITY_RANK,
|
|
11
|
-
VALID_REGISTERS,
|
|
12
|
-
fnv1aHex,
|
|
13
|
-
codePointLength,
|
|
14
|
-
detectModality,
|
|
15
|
-
defaultPackForModality,
|
|
16
|
-
isLongFormHtmlDocument,
|
|
17
|
-
hasEmbeddedUiMarkup,
|
|
18
|
-
deriveFixStrategy,
|
|
19
|
-
computeRulesetHash,
|
|
20
|
-
validateConfig,
|
|
21
|
-
resolveRegister,
|
|
22
|
-
applyRegisterOverride,
|
|
23
|
-
getScenarioStrategy,
|
|
24
|
-
computeFindingConfidence,
|
|
25
|
-
buildFindingRevision,
|
|
26
|
-
resolveEffectivePack,
|
|
27
|
-
buildZones,
|
|
28
|
-
auditText,
|
|
29
|
-
auditOoxmlEntries,
|
|
30
|
-
auditImageDocument,
|
|
31
|
-
auditPdfDocument,
|
|
32
|
-
analyzeTextProfile,
|
|
33
|
-
verifyRevision,
|
|
34
|
-
verifyRevisionBundle,
|
|
35
|
-
formatReport,
|
|
36
|
-
buildCatalog,
|
|
37
|
-
queryCatalog,
|
|
38
|
-
extractVoiceProfileOffline,
|
|
39
|
-
} from "../src/core.mjs";
|
|
40
|
-
import { analyzePatternProfile, auditPatterns } from "../src/pattern-engine.mjs";
|
|
41
|
-
import {
|
|
42
|
-
analyzeDocumentWithPocketModels,
|
|
43
|
-
predictPackWithPocketRouter,
|
|
44
|
-
} from "../src/pocket-model.mjs";
|
|
45
|
-
import {
|
|
46
|
-
LOCAL_MODEL_TIERS,
|
|
47
|
-
buildModelStatusReport,
|
|
48
|
-
installOptionalModel,
|
|
49
|
-
importLocalModelFile,
|
|
50
|
-
removeInstalledModel,
|
|
51
|
-
runLocalDeslop,
|
|
52
|
-
} from "../src/local-model.mjs";
|
|
53
|
-
import { applyReview, prepareEdits, requirePicker } from "../src/review-apply.mjs";
|
|
54
|
-
import { parseImageBuffer, parsePdfBuffer, readZipXmlEntries } from "../src/binary-node.mjs";
|
|
55
|
-
import {
|
|
56
|
-
resolveProviderConfig,
|
|
57
|
-
inspectByokEnvStatus,
|
|
58
|
-
extractOoxmlReviewText,
|
|
59
|
-
chunkTextByParagraphs,
|
|
60
|
-
buildReviewPrompt,
|
|
61
|
-
runReviewRequest,
|
|
62
|
-
validateAndNormalizeReviewResponse,
|
|
63
|
-
assertLoopbackEndpoint,
|
|
64
|
-
scrubSecrets,
|
|
65
|
-
pingEndpointHealth,
|
|
66
|
-
} from "../src/review-client.mjs";
|
|
2
|
+
import { runCli } from "../src/cli-main.mjs";
|
|
67
3
|
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const PATTERNS_DIR = path.join(REPO_ROOT, "patterns");
|
|
72
|
-
|
|
73
|
-
const DEFAULT_IGNORE_DIRS = new Set([
|
|
74
|
-
".git",
|
|
75
|
-
"node_modules",
|
|
76
|
-
".venv",
|
|
77
|
-
"venv",
|
|
78
|
-
"__pycache__",
|
|
79
|
-
".pytest_cache",
|
|
80
|
-
".mypy_cache",
|
|
81
|
-
]);
|
|
82
|
-
|
|
83
|
-
function loadAllPacks(customPacksDir = PACKS_DIR) {
|
|
84
|
-
const packs = {};
|
|
85
|
-
if (!fs.existsSync(customPacksDir)) return packs;
|
|
86
|
-
for (const entry of fs.readdirSync(customPacksDir, { withFileTypes: true })) {
|
|
87
|
-
if (!entry.isDirectory()) continue;
|
|
88
|
-
const manifestPath = path.join(customPacksDir, entry.name, "pack.json");
|
|
89
|
-
if (fs.existsSync(manifestPath)) {
|
|
90
|
-
const data = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
|
91
|
-
packs[data.id] = data;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return packs;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function loadPatternLibrary(customPatternsDir = PATTERNS_DIR) {
|
|
98
|
-
const dimDir = path.join(customPatternsDir, "dimensions");
|
|
99
|
-
const byRuleId = {};
|
|
100
|
-
if (!fs.existsSync(dimDir)) return byRuleId;
|
|
101
|
-
for (const entry of fs.readdirSync(dimDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
102
|
-
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
103
|
-
const data = JSON.parse(fs.readFileSync(path.join(dimDir, entry.name), "utf8"));
|
|
104
|
-
const dim = data.dimension || null;
|
|
105
|
-
for (const pat of data.patterns || []) {
|
|
106
|
-
if (pat.ruleId) {
|
|
107
|
-
byRuleId[pat.ruleId] = { dimension: dim, ...pat };
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return byRuleId;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function getUserConfigDir() {
|
|
115
|
-
if (process.env.DISLOP_CONFIG_HOME) {
|
|
116
|
-
return path.resolve(process.env.DISLOP_CONFIG_HOME);
|
|
117
|
-
}
|
|
118
|
-
const base = process.env.XDG_CONFIG_HOME ? path.resolve(process.env.XDG_CONFIG_HOME) : path.join(os.homedir(), ".config");
|
|
119
|
-
return path.join(base, "dislop");
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function shouldSkipUserConfig(cwd, explicitConfigPath = null) {
|
|
123
|
-
if (explicitConfigPath || process.env.DISLOP_NO_USER_CONFIG === "1") return true;
|
|
124
|
-
const isSelfRepo =
|
|
125
|
-
fs.existsSync(path.join(cwd, "packs", "core", "pack.json")) &&
|
|
126
|
-
fs.existsSync(path.join(cwd, "src", "core.mjs"));
|
|
127
|
-
return isSelfRepo && !process.env.DISLOP_CONFIG_HOME;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function mergeConfigLayers(base, layer) {
|
|
131
|
-
if (!layer || typeof layer !== "object") return base;
|
|
132
|
-
return {
|
|
133
|
-
...base,
|
|
134
|
-
...layer,
|
|
135
|
-
rules: { ...(base.rules || {}), ...(layer.rules || {}) },
|
|
136
|
-
allow: [...(base.allow || []), ...(layer.allow || [])],
|
|
137
|
-
ignore: [...(base.ignore || []), ...(layer.ignore || [])],
|
|
138
|
-
forbid: [...(base.forbid || []), ...(layer.forbid || [])],
|
|
139
|
-
overrides: [...(base.overrides || []), ...(layer.overrides || [])],
|
|
140
|
-
proseFences: [...(base.proseFences || []), ...(layer.proseFences || [])],
|
|
141
|
-
...(layer.maskBlockquotes !== undefined ? { maskBlockquotes: layer.maskBlockquotes } : {}),
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
class ConfigError extends Error {}
|
|
146
|
-
|
|
147
|
-
function readConfigJson(filePath) {
|
|
148
|
-
let raw;
|
|
149
|
-
try {
|
|
150
|
-
raw = fs.readFileSync(filePath, "utf8");
|
|
151
|
-
} catch (err) {
|
|
152
|
-
throw new ConfigError(`cannot read config '${filePath}': ${err.message}`);
|
|
153
|
-
}
|
|
154
|
-
let parsed;
|
|
155
|
-
try {
|
|
156
|
-
parsed = JSON.parse(raw);
|
|
157
|
-
} catch (err) {
|
|
158
|
-
throw new ConfigError(`invalid config '${filePath}': ${err.message}`);
|
|
159
|
-
}
|
|
160
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
161
|
-
throw new ConfigError(`invalid config '${filePath}': expected a JSON object`);
|
|
162
|
-
}
|
|
163
|
-
return parsed;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function loadConfig(cwd = process.cwd(), explicitConfigPath = null) {
|
|
167
|
-
let base = {};
|
|
168
|
-
if (!shouldSkipUserConfig(cwd, explicitConfigPath)) {
|
|
169
|
-
const userCfgPath = path.join(getUserConfigDir(), "config.json");
|
|
170
|
-
if (fs.existsSync(userCfgPath)) {
|
|
171
|
-
base = mergeConfigLayers(base, readConfigJson(userCfgPath));
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
if (explicitConfigPath) {
|
|
175
|
-
const resolved = path.resolve(cwd, explicitConfigPath);
|
|
176
|
-
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
|
|
177
|
-
throw new ConfigError(`config file not found: ${explicitConfigPath}`);
|
|
178
|
-
}
|
|
179
|
-
base = mergeConfigLayers(base, readConfigJson(resolved));
|
|
180
|
-
} else {
|
|
181
|
-
const candidates = [
|
|
182
|
-
path.join(cwd, ".dislop.json"),
|
|
183
|
-
path.join(cwd, "dislop.json"),
|
|
184
|
-
path.join(cwd, ".disloprc.json"),
|
|
185
|
-
];
|
|
186
|
-
for (const candidate of candidates) {
|
|
187
|
-
if (fs.existsSync(candidate)) {
|
|
188
|
-
base = mergeConfigLayers(base, readConfigJson(candidate));
|
|
189
|
-
break;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const localPath = path.join(cwd, ".dislop.local.json");
|
|
195
|
-
if (fs.existsSync(localPath)) {
|
|
196
|
-
base = mergeConfigLayers(base, readConfigJson(localPath));
|
|
197
|
-
}
|
|
198
|
-
try {
|
|
199
|
-
return validateConfig(base);
|
|
200
|
-
} catch (err) {
|
|
201
|
-
throw new ConfigError(err.message);
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function loadConfigOrExit(cwd = process.cwd(), explicitConfigPath = null) {
|
|
206
|
-
try {
|
|
207
|
-
return loadConfig(cwd, explicitConfigPath);
|
|
208
|
-
} catch (err) {
|
|
209
|
-
console.error(`dislop: ${err.message}`);
|
|
210
|
-
process.exit(2);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
function summarizeReportContext(regPairs = [], flagRegister = null) {
|
|
215
|
-
if (flagRegister && String(flagRegister).trim().toLowerCase() !== "auto") {
|
|
216
|
-
return { register: String(flagRegister).trim().toLowerCase(), registerSource: "flag" };
|
|
217
|
-
}
|
|
218
|
-
if (!regPairs || regPairs.length === 0) {
|
|
219
|
-
return { register: "unspecified", registerSource: "default" };
|
|
220
|
-
}
|
|
221
|
-
const regs = new Set(regPairs.map((r) => r.register));
|
|
222
|
-
const srcs = new Set(regPairs.map((r) => r.registerSource));
|
|
223
|
-
if (regs.size === 1) {
|
|
224
|
-
const register = regPairs[0].register;
|
|
225
|
-
const registerSource = srcs.size === 1 ? regPairs[0].registerSource : "mixed";
|
|
226
|
-
return { register, registerSource };
|
|
227
|
-
}
|
|
228
|
-
return { register: "mixed", registerSource: "mixed" };
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
function discoverVoiceCard(cwd = process.cwd()) {
|
|
232
|
-
const candidates = [
|
|
233
|
-
["local", path.join(cwd, ".dislop.local", "voice.json")],
|
|
234
|
-
["project", path.join(cwd, ".dislop", "voice.json")],
|
|
235
|
-
];
|
|
236
|
-
if (!shouldSkipUserConfig(cwd, null)) {
|
|
237
|
-
candidates.push(["user", path.join(getUserConfigDir(), "voice.json")]);
|
|
238
|
-
}
|
|
239
|
-
for (const [scope, p] of candidates) {
|
|
240
|
-
if (fs.existsSync(p)) {
|
|
241
|
-
try {
|
|
242
|
-
const card = JSON.parse(fs.readFileSync(p, "utf8"));
|
|
243
|
-
if (card && typeof card === "object" && !Array.isArray(card)) {
|
|
244
|
-
return { found: true, scope, card };
|
|
245
|
-
}
|
|
246
|
-
} catch {
|
|
247
|
-
// ignore unreadable voice card
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
return { found: false, scope: null, card: null };
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
function expandBraces(pattern) {
|
|
255
|
-
const m = pattern.match(/\{([^{}]+)\}/);
|
|
256
|
-
if (!m) return [pattern];
|
|
257
|
-
const prefix = pattern.slice(0, m.index);
|
|
258
|
-
const suffix = pattern.slice(m.index + m[0].length);
|
|
259
|
-
return m[1].split(",").flatMap((part) => expandBraces(prefix + part.trim() + suffix));
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
function globToRegExp(glob) {
|
|
263
|
-
const norm = glob.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
264
|
-
let rx = "^";
|
|
265
|
-
for (let i = 0; i < norm.length; i += 1) {
|
|
266
|
-
const ch = norm[i];
|
|
267
|
-
if (ch === "*" && norm[i + 1] === "*") {
|
|
268
|
-
if (norm[i + 2] === "/") {
|
|
269
|
-
rx += "(?:.+/)?";
|
|
270
|
-
i += 2;
|
|
271
|
-
} else {
|
|
272
|
-
rx += ".*";
|
|
273
|
-
i += 1;
|
|
274
|
-
}
|
|
275
|
-
} else if (ch === "*") {
|
|
276
|
-
rx += "[^/]*";
|
|
277
|
-
} else if (ch === "?") {
|
|
278
|
-
rx += "[^/]";
|
|
279
|
-
} else if ("+.^$|()[]{}".includes(ch)) {
|
|
280
|
-
rx += "\\" + ch;
|
|
281
|
-
} else {
|
|
282
|
-
rx += ch;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
rx += "$";
|
|
286
|
-
return new RegExp(rx);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function matchesAnyGlob(relPosix, globs = []) {
|
|
290
|
-
const clean = relPosix.replace(/^\.\//, "");
|
|
291
|
-
return globs.flatMap(expandBraces).some((g) => globToRegExp(g).test(clean));
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
function resolveConfigForFile(relPosix, config = {}) {
|
|
295
|
-
let merged = {
|
|
296
|
-
...config,
|
|
297
|
-
rules: { ...(config.rules || {}) },
|
|
298
|
-
allow: [...(config.allow || [])],
|
|
299
|
-
forbid: [...(config.forbid || [])],
|
|
300
|
-
proseFences: [...(config.proseFences || [])],
|
|
301
|
-
};
|
|
302
|
-
for (const ov of config?.overrides || []) {
|
|
303
|
-
const patterns = Array.isArray(ov.files) ? ov.files : [ov.files];
|
|
304
|
-
if (!matchesAnyGlob(relPosix, patterns)) continue;
|
|
305
|
-
merged = {
|
|
306
|
-
...merged,
|
|
307
|
-
...(ov.pack ? { pack: ov.pack } : {}),
|
|
308
|
-
rules: { ...merged.rules, ...(ov.rules || {}) },
|
|
309
|
-
allow: [...merged.allow, ...(ov.allow || [])],
|
|
310
|
-
forbid: [...merged.forbid, ...(ov.forbid || [])],
|
|
311
|
-
proseFences: [...merged.proseFences, ...(ov.proseFences || [])],
|
|
312
|
-
...(ov.maskBlockquotes !== undefined ? { maskBlockquotes: ov.maskBlockquotes } : {}),
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
return merged;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
function mergePacks(primaryPack, extraPack) {
|
|
319
|
-
const byId = new Map();
|
|
320
|
-
for (const r of extraPack.rules || []) byId.set(r.id, r);
|
|
321
|
-
for (const r of primaryPack.rules || []) byId.set(r.id, r);
|
|
322
|
-
return {
|
|
323
|
-
...extraPack,
|
|
324
|
-
...primaryPack,
|
|
325
|
-
id: `${primaryPack.id}+${extraPack.id}`,
|
|
326
|
-
thresholds: { ...(extraPack.thresholds || {}), ...(primaryPack.thresholds || {}) },
|
|
327
|
-
rules: Array.from(byId.values()),
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function pickPackForFile(relPosix, modality, explicitPack, config) {
|
|
332
|
-
if (explicitPack && explicitPack !== "auto") return explicitPack;
|
|
333
|
-
const resolvedCfg = resolveConfigForFile(relPosix, config);
|
|
334
|
-
if (resolvedCfg?.pack && explicitPack !== "auto") return resolvedCfg.pack;
|
|
335
|
-
return defaultPackForModality(modality);
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
function decodeUtf8Strict(buffer) {
|
|
339
|
-
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
340
|
-
return decoder.decode(buffer);
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
function collectFiles(targetPaths, cwd, config, explicitTargets = true) {
|
|
344
|
-
const realCwd = fs.existsSync(cwd) ? fs.realpathSync(cwd) : cwd;
|
|
345
|
-
const files = [];
|
|
346
|
-
const skipped = [];
|
|
347
|
-
const ignoreGlobs = config?.ignore || [];
|
|
348
|
-
|
|
349
|
-
// When running inside the dislop repo itself without custom config, skip intentional bad-example dirs
|
|
350
|
-
const isSelfRepo =
|
|
351
|
-
fs.existsSync(path.join(realCwd, "packs", "core", "pack.json")) &&
|
|
352
|
-
fs.existsSync(path.join(realCwd, "src", "core.mjs"));
|
|
353
|
-
const effectiveIgnores = isSelfRepo && ignoreGlobs.length === 0
|
|
354
|
-
? ["packs/**", "tests/**", "scratch/**"]
|
|
355
|
-
: ignoreGlobs;
|
|
356
|
-
|
|
357
|
-
function walk(absPath, explicit) {
|
|
358
|
-
if (!fs.existsSync(absPath)) {
|
|
359
|
-
throw new Error(`Target path not found: ${absPath}`);
|
|
360
|
-
}
|
|
361
|
-
const canonicalPath = fs.realpathSync(absPath);
|
|
362
|
-
const stat = fs.statSync(canonicalPath);
|
|
363
|
-
const rawRel = path.relative(realCwd, canonicalPath);
|
|
364
|
-
const rel =
|
|
365
|
-
!rawRel || rawRel === "."
|
|
366
|
-
? path.basename(canonicalPath)
|
|
367
|
-
: rawRel === ".." || rawRel.startsWith(`..${path.sep}`) || path.isAbsolute(rawRel)
|
|
368
|
-
? path.basename(canonicalPath)
|
|
369
|
-
: rawRel.split(path.sep).join("/");
|
|
370
|
-
|
|
371
|
-
if (!explicit && matchesAnyGlob(rel, effectiveIgnores)) {
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
if (stat.isDirectory()) {
|
|
376
|
-
const entries = fs
|
|
377
|
-
.readdirSync(canonicalPath, { withFileTypes: true })
|
|
378
|
-
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
379
|
-
for (const entry of entries) {
|
|
380
|
-
if (DEFAULT_IGNORE_DIRS.has(entry.name)) continue;
|
|
381
|
-
walk(path.join(canonicalPath, entry.name), false);
|
|
382
|
-
}
|
|
383
|
-
return;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
if (!stat.isFile()) return;
|
|
387
|
-
const mod = detectModality(canonicalPath);
|
|
388
|
-
if (!mod) {
|
|
389
|
-
if (explicit) {
|
|
390
|
-
skipped.push({ file: rel, reason: `Unsupported file extension '${path.extname(canonicalPath) || "(none)"}'` });
|
|
391
|
-
}
|
|
392
|
-
return;
|
|
393
|
-
}
|
|
394
|
-
files.push({ absPath: canonicalPath, rel, modality: mod, explicit });
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
for (const t of targetPaths) {
|
|
398
|
-
walk(path.resolve(realCwd, t), explicitTargets);
|
|
399
|
-
}
|
|
400
|
-
return { files, skipped };
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
const PROSE_ML_MODALITIES = new Set(["markdown", "text", "html", "svg"]);
|
|
404
|
-
|
|
405
|
-
function buildCodepointLineStarts(text) {
|
|
406
|
-
const starts = [0];
|
|
407
|
-
let cpIdx = 0;
|
|
408
|
-
for (const ch of String(text || "")) {
|
|
409
|
-
cpIdx += 1;
|
|
410
|
-
if (ch === "\n") starts.push(cpIdx);
|
|
411
|
-
}
|
|
412
|
-
return starts;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
function cpOffsetToLine(cpStarts, cpOff) {
|
|
416
|
-
let lo = 0;
|
|
417
|
-
let hi = cpStarts.length - 1;
|
|
418
|
-
while (lo <= hi) {
|
|
419
|
-
const mid = (lo + hi) >> 1;
|
|
420
|
-
if (cpStarts[mid] <= cpOff) lo = mid + 1;
|
|
421
|
-
else hi = mid - 1;
|
|
422
|
-
}
|
|
423
|
-
return Math.max(0, hi) + 1;
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
function unquoteGitPath(rawPath) {
|
|
427
|
-
const s = String(rawPath || "");
|
|
428
|
-
if (s.length < 2 || !s.startsWith('"') || !s.endsWith('"')) return s;
|
|
429
|
-
const inner = s.slice(1, -1);
|
|
430
|
-
const bytes = [];
|
|
431
|
-
const pushStr = (str) => {
|
|
432
|
-
for (const b of Buffer.from(str, "utf8")) bytes.push(b);
|
|
433
|
-
};
|
|
434
|
-
const escMap = { a: "\x07", b: "\x08", f: "\x0c", n: "\n", r: "\r", t: "\t", v: "\x0b", "\\": "\\", '"': '"' };
|
|
435
|
-
for (let i = 0; i < inner.length; i += 1) {
|
|
436
|
-
const ch = inner[i];
|
|
437
|
-
if (ch !== "\\") {
|
|
438
|
-
pushStr(ch);
|
|
439
|
-
continue;
|
|
440
|
-
}
|
|
441
|
-
if (i + 1 >= inner.length) {
|
|
442
|
-
bytes.push(0x5c);
|
|
443
|
-
break;
|
|
444
|
-
}
|
|
445
|
-
const next = inner[i + 1];
|
|
446
|
-
if (/[0-7]{3}/.test(inner.slice(i + 1, i + 4))) {
|
|
447
|
-
bytes.push(parseInt(inner.slice(i + 1, i + 4), 8));
|
|
448
|
-
i += 3;
|
|
449
|
-
} else if (next in escMap) {
|
|
450
|
-
pushStr(escMap[next]);
|
|
451
|
-
i += 1;
|
|
452
|
-
} else {
|
|
453
|
-
pushStr(next);
|
|
454
|
-
i += 1;
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
return Buffer.from(bytes).toString("utf8");
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
function getChangedLineMap(cwd, gitRef, staged = false) {
|
|
461
|
-
const args = staged
|
|
462
|
-
? [
|
|
463
|
-
"-c", "core.quotepath=off",
|
|
464
|
-
"-c", "diff.interHunkContext=0",
|
|
465
|
-
"diff", "--cached",
|
|
466
|
-
"--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "--relative",
|
|
467
|
-
"-U0", "--no-color", "--",
|
|
468
|
-
]
|
|
469
|
-
: [
|
|
470
|
-
"-c", "core.quotepath=off",
|
|
471
|
-
"-c", "diff.interHunkContext=0",
|
|
472
|
-
"diff",
|
|
473
|
-
"--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "--relative",
|
|
474
|
-
"-U0", "--no-color", gitRef || "HEAD", "--",
|
|
475
|
-
];
|
|
476
|
-
const diffOut = execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 32 * 1024 * 1024 });
|
|
477
|
-
const changed = new Map(); // relPath -> Set<line> | "ALL"
|
|
478
|
-
let currentFile = null;
|
|
479
|
-
let inHunk = false;
|
|
480
|
-
|
|
481
|
-
for (const line of diffOut.split(/\r?\n/)) {
|
|
482
|
-
if (line.startsWith("diff --git ")) {
|
|
483
|
-
inHunk = false;
|
|
484
|
-
currentFile = null;
|
|
485
|
-
} else if (!inHunk && (line.startsWith("+++ b/") || line.startsWith('+++ "b/'))) {
|
|
486
|
-
const target = unquoteGitPath(line.slice(4));
|
|
487
|
-
if (target.startsWith("b/")) {
|
|
488
|
-
currentFile = target.slice(2);
|
|
489
|
-
if (!changed.has(currentFile)) changed.set(currentFile, new Set());
|
|
490
|
-
}
|
|
491
|
-
} else if (!inHunk && line.startsWith("Binary files ")) {
|
|
492
|
-
const bm = line.match(/^Binary files .* and (b\/.+|"b\/.+") differ$/);
|
|
493
|
-
if (bm) {
|
|
494
|
-
const binTarget = unquoteGitPath(bm[1]);
|
|
495
|
-
if (binTarget.startsWith("b/")) {
|
|
496
|
-
changed.set(binTarget.slice(2), "ALL");
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
} else if (line.startsWith("@@ ") && currentFile) {
|
|
500
|
-
inHunk = true;
|
|
501
|
-
const m = line.match(/\+(\d+)(?:,(\d+))?/);
|
|
502
|
-
if (m) {
|
|
503
|
-
const start = Number(m[1]);
|
|
504
|
-
const count = m[2] !== undefined ? Number(m[2]) : 1;
|
|
505
|
-
if (count === 0) continue;
|
|
506
|
-
const set = changed.get(currentFile);
|
|
507
|
-
if (set instanceof Set) {
|
|
508
|
-
for (let k = 0; k < count; k += 1) {
|
|
509
|
-
set.add(start + k);
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
return changed;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
function filterDriversWithProfile(drivers, profile) {
|
|
519
|
-
if (!Array.isArray(drivers) || !profile) return drivers || [];
|
|
520
|
-
return drivers.filter((d) => {
|
|
521
|
-
const feat = String(d.feature || "");
|
|
522
|
-
if (profile.concreteness?.status === "grounded" && feat.includes("concreteness")) {
|
|
523
|
-
return false;
|
|
524
|
-
}
|
|
525
|
-
if (profile.burstiness?.status === "varied" && feat.includes("sent_cv")) {
|
|
526
|
-
return false;
|
|
527
|
-
}
|
|
528
|
-
return true;
|
|
529
|
-
});
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
function buildPocketMlFindings(text, filename, existingFindings, threshold = null, { profile = null, modality = null, register = "unspecified" } = {}) {
|
|
533
|
-
if (register === "technical") {
|
|
534
|
-
return { doc: { documentProbability: 0, paragraphs: [], flaggedCount: 0 }, findings: [] };
|
|
535
|
-
}
|
|
536
|
-
const doc = analyzeDocumentWithPocketModels(text, { threshold });
|
|
537
|
-
const extras = [];
|
|
538
|
-
const textLines = String(text || "").split(/\r?\n/);
|
|
539
|
-
for (const p of doc.paragraphs) {
|
|
540
|
-
if (!p.flagged) continue;
|
|
541
|
-
const overlapsExisting = existingFindings.some(
|
|
542
|
-
(f) => f.line >= p.startLine && f.line <= p.endLine
|
|
543
|
-
);
|
|
544
|
-
if (overlapsExisting) continue;
|
|
545
|
-
const pct = Math.round(p.slopProbability * 100);
|
|
546
|
-
const activeDrivers = filterDriversWithProfile(p.topDrivers, profile);
|
|
547
|
-
const drvEn = activeDrivers.map((d) => d.reason.en).join("; ") || "uniform abstract phrasing";
|
|
548
|
-
const drvZh = activeDrivers.map((d) => d.reason.zh).join("、") || "句式与用词高度均质";
|
|
549
|
-
const loc = String(p.startLine);
|
|
550
|
-
const cleanExcerpt = String(p.excerpt || "");
|
|
551
|
-
const fullPara = textLines.slice(Math.max(0, p.startLine - 1), p.endLine).join("\n") || cleanExcerpt;
|
|
552
|
-
const fp = `pocket-stealth-vapor:${fnv1aHex(`pocket-stealth-vapor|${cleanExcerpt.toLowerCase()}|${loc}`)}`;
|
|
553
|
-
const msgObj = {
|
|
554
|
-
en: `Paragraph reads as predictable low-concreteness AI filler (${pct}% pocket-ML score: ${drvEn}).`,
|
|
555
|
-
zh: `段落呈高度可预测、低事实密度的温吞水套话(内置模型评分 ${pct}%:${drvZh})。`,
|
|
556
|
-
};
|
|
557
|
-
const delObj = {
|
|
558
|
-
en: "Cut this paragraph or replace abstract cushion wrappers with one concrete event, number, file path, or direct action.",
|
|
559
|
-
zh: "删掉整段空泛铺垫,或把抽象缓冲外壳直接换成具体事件、数字、文件路径或明确动作。",
|
|
560
|
-
};
|
|
561
|
-
const effMod = modality || detectModality(filename) || "markdown";
|
|
562
|
-
extras.push({
|
|
563
|
-
fingerprint: fp,
|
|
564
|
-
ruleId: "pocket-stealth-vapor",
|
|
565
|
-
packId: "pocket-model",
|
|
566
|
-
severity: "warning",
|
|
567
|
-
confidence: computeFindingConfidence({ ruleId: "pocket-stealth-vapor", tier: "taste", severity: "warning" }),
|
|
568
|
-
tier: "taste",
|
|
569
|
-
fixStrategy: "rephrase",
|
|
570
|
-
family: "rhythm/pocket-stealth-vapor",
|
|
571
|
-
category: "statistical-vapor",
|
|
572
|
-
modality: effMod,
|
|
573
|
-
file: filename,
|
|
574
|
-
location: loc,
|
|
575
|
-
line: p.startLine,
|
|
576
|
-
col: 1,
|
|
577
|
-
endLine: p.endLine,
|
|
578
|
-
match: cleanExcerpt,
|
|
579
|
-
excerpt: cleanExcerpt,
|
|
580
|
-
mlProbability: p.slopProbability,
|
|
581
|
-
message: msgObj,
|
|
582
|
-
deletionTest: delObj,
|
|
583
|
-
revision: buildFindingRevision({
|
|
584
|
-
ruleId: "pocket-stealth-vapor",
|
|
585
|
-
tier: "taste",
|
|
586
|
-
family: "rhythm/pocket-stealth-vapor",
|
|
587
|
-
modality: effMod,
|
|
588
|
-
message: msgObj,
|
|
589
|
-
deletionTest: delObj,
|
|
590
|
-
sentence: fullPara,
|
|
591
|
-
fixStrategy: "rephrase",
|
|
592
|
-
}),
|
|
593
|
-
});
|
|
594
|
-
}
|
|
595
|
-
return { doc, findings: extras };
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
function summarizePocketForProfile(text) {
|
|
599
|
-
const doc = analyzeDocumentWithPocketModels(text);
|
|
600
|
-
return {
|
|
601
|
-
documentProbability: doc.documentProbability,
|
|
602
|
-
band: doc.wholeTextScore.band,
|
|
603
|
-
recommendedPack: doc.packRouter.recommendedPack,
|
|
604
|
-
flaggedCount: doc.flaggedCount,
|
|
605
|
-
};
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
function lookupRuleAcrossPacks(packs, pack, ruleId) {
|
|
609
|
-
const inPack = (pack?.rules || []).find((r) => r.id === ruleId);
|
|
610
|
-
if (inPack) return inPack;
|
|
611
|
-
for (const p of Object.values(packs || {})) {
|
|
612
|
-
const found = (p?.rules || []).find((r) => r.id === ruleId);
|
|
613
|
-
if (found) return found;
|
|
614
|
-
}
|
|
615
|
-
return null;
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
function mergePatternBankFindings(existingFindings, patFindings, { packs = null, pack = null, register = "unspecified", config = {} } = {}) {
|
|
619
|
-
const seen = new Set(existingFindings.map((f) => `${f.ruleId}:${f.line}`));
|
|
620
|
-
const out = [...existingFindings];
|
|
621
|
-
for (const pf of patFindings || []) {
|
|
622
|
-
const key = `${pf.ruleId}:${pf.line}`;
|
|
623
|
-
if (seen.has(key)) continue;
|
|
624
|
-
const ruleRef = lookupRuleAcrossPacks(packs, pack, pf.ruleId);
|
|
625
|
-
let registerAdjusted = false;
|
|
626
|
-
let effSev = pf.severity || "info";
|
|
627
|
-
let effMsg = pf.message;
|
|
628
|
-
let effDel = pf.deletionTest || ruleRef?.deletionTest || null;
|
|
629
|
-
if (ruleRef) {
|
|
630
|
-
const regApplied = applyRegisterOverride(ruleRef, register, config);
|
|
631
|
-
if (regApplied.skip) continue;
|
|
632
|
-
if (regApplied.registerAdjusted) {
|
|
633
|
-
registerAdjusted = true;
|
|
634
|
-
effSev = regApplied.rule.severity || effSev;
|
|
635
|
-
if (regApplied.rule.message) effMsg = regApplied.rule.message;
|
|
636
|
-
if (regApplied.rule.deletionTest) effDel = regApplied.rule.deletionTest;
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
seen.add(key);
|
|
640
|
-
const fam = pf.family || (pf.dimension ? `${pf.dimension}/${pf.ruleId}` : "pattern-bank");
|
|
641
|
-
const mod = pf.modality || "markdown";
|
|
642
|
-
const revScope =
|
|
643
|
-
ruleRef?.revisionScope ||
|
|
644
|
-
(pf.ruleId === "low-burstiness-vapor" ? "paragraph" : null);
|
|
645
|
-
const fixStrat = pf.fixStrategy || deriveFixStrategy({ id: pf.ruleId, family: fam });
|
|
646
|
-
out.push({
|
|
647
|
-
...pf,
|
|
648
|
-
severity: effSev,
|
|
649
|
-
fixStrategy: fixStrat,
|
|
650
|
-
message: effMsg,
|
|
651
|
-
...(effDel ? { deletionTest: effDel } : {}),
|
|
652
|
-
confidence: pf.confidence || computeFindingConfidence({ ruleId: pf.ruleId, tier: pf.tier || "taste", severity: effSev, registerAdjusted }),
|
|
653
|
-
revision:
|
|
654
|
-
pf.revision ||
|
|
655
|
-
buildFindingRevision({
|
|
656
|
-
ruleId: pf.ruleId,
|
|
657
|
-
tier: pf.tier || "taste",
|
|
658
|
-
family: fam,
|
|
659
|
-
modality: mod,
|
|
660
|
-
message: effMsg,
|
|
661
|
-
deletionTest: effDel,
|
|
662
|
-
sentence: String(pf.match || ""),
|
|
663
|
-
revisionKind: ruleRef?.revisionKind || null,
|
|
664
|
-
revisionScope: revScope,
|
|
665
|
-
revisionAvoid: ruleRef?.revisionAvoid || null,
|
|
666
|
-
fixStrategy: fixStrat,
|
|
667
|
-
}),
|
|
668
|
-
});
|
|
669
|
-
}
|
|
670
|
-
return out;
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
function collectTextCoverageWarnings(text, modality, rel, profile) {
|
|
674
|
-
const warnings = [];
|
|
675
|
-
if (
|
|
676
|
-
modality === "html" &&
|
|
677
|
-
/<script\b[^>]*\btype\s*=\s*(?:"application\/json"|'application\/json'|application\/json(?=[\s>]))/i.test(text)
|
|
678
|
-
) {
|
|
679
|
-
const zones = buildZones(text, "html");
|
|
680
|
-
if (codePointLength(zones.prose.replace(/\s+/g, "")) < 120) {
|
|
681
|
-
warnings.push({
|
|
682
|
-
file: rel,
|
|
683
|
-
code: "spa-json-shell",
|
|
684
|
-
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.",
|
|
685
|
-
});
|
|
686
|
-
return warnings;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
const textCpLen = codePointLength(text);
|
|
690
|
-
if ((modality === "markdown" || modality === "text" || modality === "html") && textCpLen >= 2000 && profile && profile.proseCoverage < 0.15) {
|
|
691
|
-
if (modality === "html") {
|
|
692
|
-
warnings.push({
|
|
693
|
-
file: rel,
|
|
694
|
-
code: "low-prose-coverage",
|
|
695
|
-
message: `Extracted prose covers only ${Math.round(profile.proseCoverage * 100)}% of file (${textCpLen} chars); check fenced blocks/markup if unexpected.`,
|
|
696
|
-
});
|
|
697
|
-
return warnings;
|
|
698
|
-
}
|
|
699
|
-
const nonEmptyLines = text.split(/\r?\n/).filter((l) => l.trim().length > 0);
|
|
700
|
-
const tableOrLinkLines = nonEmptyLines.filter((l) => /^\s*(?:\||[-*+]\s+\[)/.test(l)).length;
|
|
701
|
-
if (nonEmptyLines.length > 0 && tableOrLinkLines / nonEmptyLines.length < 0.5) {
|
|
702
|
-
warnings.push({
|
|
703
|
-
file: rel,
|
|
704
|
-
code: "low-prose-coverage",
|
|
705
|
-
message: `Extracted prose covers only ${Math.round(profile.proseCoverage * 100)}% of file (${textCpLen} chars); check fenced blocks/markup if unexpected.`,
|
|
706
|
-
});
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
return warnings;
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
function selectPackWithConfidenceFloor(routeRes) {
|
|
713
|
-
const rec = routeRes?.recommendedPack || "business-brief";
|
|
714
|
-
const conf = Number(routeRes?.confidence || 0);
|
|
715
|
-
if (rec === "business-brief") return { packId: "business-brief", packSource: "auto-pocket-router" };
|
|
716
|
-
if (rec === "deck-and-ui" && conf >= 0.6) return { packId: "deck-and-ui", packSource: "auto-pocket-router" };
|
|
717
|
-
if (rec !== "deck-and-ui" && conf >= 0.65) return { packId: rec, packSource: "auto-pocket-router" };
|
|
718
|
-
return { packId: "business-brief", packSource: "auto-default-fallback" };
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
function resolveTextPackAndSource(text, rel, modality, explicitPack, fileConfig, packs) {
|
|
722
|
-
let pack;
|
|
723
|
-
let effectivePack;
|
|
724
|
-
let packSource;
|
|
725
|
-
if (explicitPack && explicitPack !== "auto") {
|
|
726
|
-
pack = resolveEffectivePack(explicitPack, packs, fileConfig);
|
|
727
|
-
effectivePack = explicitPack;
|
|
728
|
-
packSource = "cli-flag";
|
|
729
|
-
} else if (explicitPack === "auto" && (modality === "markdown" || modality === "text")) {
|
|
730
|
-
const sel = selectPackWithConfidenceFloor(predictPackWithPocketRouter(text));
|
|
731
|
-
const routed = sel.packId;
|
|
732
|
-
if (modality === "markdown" && hasEmbeddedUiMarkup(text)) {
|
|
733
|
-
let prosePackId = routed;
|
|
734
|
-
if (prosePackId === "deck-and-ui") {
|
|
735
|
-
const stripped = text.replace(/<[^>]+>/g, " ");
|
|
736
|
-
const strippedCjk = (stripped.match(/[\u4e00-\u9fff]/gu) || []).length;
|
|
737
|
-
const strippedWords = stripped.split(/\s+/).filter((w) => /[A-Za-z0-9]/.test(w)).length;
|
|
738
|
-
if (strippedCjk >= 20 || strippedWords >= 12) {
|
|
739
|
-
const rerouted = selectPackWithConfidenceFloor(predictPackWithPocketRouter(stripped)).packId;
|
|
740
|
-
prosePackId = rerouted === "deck-and-ui" ? "business-brief" : rerouted;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
if (prosePackId !== "deck-and-ui") {
|
|
744
|
-
const prosePack = resolveEffectivePack(prosePackId, packs, fileConfig);
|
|
745
|
-
const uiPack = resolveEffectivePack("deck-and-ui", packs, fileConfig);
|
|
746
|
-
pack = mergePacks(prosePack, uiPack);
|
|
747
|
-
effectivePack = `${prosePackId}+deck-and-ui`;
|
|
748
|
-
packSource = "auto-mixed-ui";
|
|
749
|
-
} else {
|
|
750
|
-
pack = resolveEffectivePack(routed, packs, fileConfig);
|
|
751
|
-
effectivePack = routed;
|
|
752
|
-
packSource = sel.packSource;
|
|
753
|
-
}
|
|
754
|
-
} else {
|
|
755
|
-
pack = resolveEffectivePack(routed, packs, fileConfig);
|
|
756
|
-
effectivePack = routed;
|
|
757
|
-
packSource = sel.packSource;
|
|
758
|
-
}
|
|
759
|
-
} else if (explicitPack === "auto" && modality === "html" && isLongFormHtmlDocument(text)) {
|
|
760
|
-
const biz = resolveEffectivePack("business-brief", packs, fileConfig);
|
|
761
|
-
const ui = resolveEffectivePack("deck-and-ui", packs, fileConfig);
|
|
762
|
-
pack = mergePacks(biz, ui);
|
|
763
|
-
effectivePack = "business-brief+deck-and-ui";
|
|
764
|
-
packSource = "auto-html-longform";
|
|
765
|
-
} else {
|
|
766
|
-
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
767
|
-
pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
768
|
-
effectivePack = packId;
|
|
769
|
-
packSource = explicitPack === "auto" ? "auto-modality" : fileConfig.pack ? "config" : "default-modality";
|
|
770
|
-
}
|
|
771
|
-
return { pack, effectivePack, packSource };
|
|
4
|
+
const code = await runCli(process.argv.slice(2));
|
|
5
|
+
if (process.argv[2] !== "mcp") {
|
|
6
|
+
process.exitCode = code;
|
|
772
7
|
}
|
|
773
|
-
|
|
774
|
-
function inspectSingleFile({ absPath, rel, modality }, packs, explicitPack, config, { includeMl = false, includePatterns = false, includeProfile = false, banks = null, register = null } = {}) {
|
|
775
|
-
const stat = fs.statSync(absPath);
|
|
776
|
-
if (stat.size > 25 * 1024 * 1024) {
|
|
777
|
-
return {
|
|
778
|
-
checked: false,
|
|
779
|
-
findings: [],
|
|
780
|
-
unusedSuppressions: [],
|
|
781
|
-
coverageWarnings: [],
|
|
782
|
-
skipped: [{ file: rel, reason: "File exceeds 25 MB single-file inspection cap" }],
|
|
783
|
-
};
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
const fileConfig = resolveConfigForFile(rel, config);
|
|
787
|
-
const buf = fs.readFileSync(absPath);
|
|
788
|
-
|
|
789
|
-
if (modality === "docx" || modality === "pptx") {
|
|
790
|
-
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
791
|
-
const pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
792
|
-
const packSource = explicitPack && explicitPack !== "auto" ? "cli-flag" : explicitPack === "auto" ? "auto-modality" : fileConfig.pack ? "config" : "default-modality";
|
|
793
|
-
const regInfo = resolveRegister("", { filename: rel, flagRegister: register, config: fileConfig });
|
|
794
|
-
try {
|
|
795
|
-
const entries = readZipXmlEntries(buf);
|
|
796
|
-
const res = auditOoxmlEntries(entries, { filename: rel, modality, pack, config: fileConfig, register });
|
|
797
|
-
const missingCorePart = res.skipped.some((s) => s.file === rel);
|
|
798
|
-
let findings = res.findings;
|
|
799
|
-
if (includePatterns && !missingCorePart) {
|
|
800
|
-
const patRes = auditPatterns("", { filename: rel, modality, banks: banks || loadPatternBanks(), ooxml: entries, config: fileConfig });
|
|
801
|
-
findings = mergePatternBankFindings(findings, patRes.findings, { packs, pack, register: regInfo.register, config: fileConfig });
|
|
802
|
-
}
|
|
803
|
-
return {
|
|
804
|
-
checked: !missingCorePart,
|
|
805
|
-
findings,
|
|
806
|
-
unusedSuppressions: [],
|
|
807
|
-
coverageWarnings: [],
|
|
808
|
-
skipped: res.skipped,
|
|
809
|
-
effectivePack: packId,
|
|
810
|
-
packSource,
|
|
811
|
-
rulesetHash: computeRulesetHash(pack),
|
|
812
|
-
register: regInfo.register,
|
|
813
|
-
registerSource: regInfo.registerSource,
|
|
814
|
-
};
|
|
815
|
-
} catch (err) {
|
|
816
|
-
return {
|
|
817
|
-
checked: false,
|
|
818
|
-
findings: [],
|
|
819
|
-
unusedSuppressions: [],
|
|
820
|
-
coverageWarnings: [],
|
|
821
|
-
skipped: [{ file: rel, reason: `Uninspectable ${modality.toUpperCase()} archive: ${err.message}` }],
|
|
822
|
-
};
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
if (modality === "image") {
|
|
827
|
-
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
828
|
-
const pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
829
|
-
const packSource = explicitPack && explicitPack !== "auto" ? "cli-flag" : explicitPack === "auto" ? "auto-modality" : fileConfig.pack ? "config" : "default-modality";
|
|
830
|
-
const regInfo = resolveRegister("", { filename: rel, flagRegister: register, config: fileConfig });
|
|
831
|
-
try {
|
|
832
|
-
const parsed = parseImageBuffer(buf);
|
|
833
|
-
const res = auditImageDocument(parsed, { filename: rel, pack, config: fileConfig });
|
|
834
|
-
return {
|
|
835
|
-
checked: true,
|
|
836
|
-
findings: res.findings,
|
|
837
|
-
unusedSuppressions: [],
|
|
838
|
-
coverageWarnings: [],
|
|
839
|
-
skipped: res.skipped,
|
|
840
|
-
effectivePack: packId,
|
|
841
|
-
packSource,
|
|
842
|
-
rulesetHash: computeRulesetHash(pack),
|
|
843
|
-
register: regInfo.register,
|
|
844
|
-
registerSource: regInfo.registerSource,
|
|
845
|
-
};
|
|
846
|
-
} catch (err) {
|
|
847
|
-
return {
|
|
848
|
-
checked: false,
|
|
849
|
-
findings: [],
|
|
850
|
-
unusedSuppressions: [],
|
|
851
|
-
coverageWarnings: [],
|
|
852
|
-
skipped: [{ file: rel, reason: `Uninspectable image: ${err.message}` }],
|
|
853
|
-
};
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
if (modality === "pdf") {
|
|
858
|
-
const regInfo = resolveRegister("", { filename: rel, flagRegister: register, config: fileConfig });
|
|
859
|
-
try {
|
|
860
|
-
const parsed = parsePdfBuffer(buf);
|
|
861
|
-
let pack;
|
|
862
|
-
let effectivePack;
|
|
863
|
-
let packSource;
|
|
864
|
-
if (explicitPack && explicitPack !== "auto") {
|
|
865
|
-
pack = resolveEffectivePack(explicitPack, packs, fileConfig);
|
|
866
|
-
effectivePack = explicitPack;
|
|
867
|
-
packSource = "cli-flag";
|
|
868
|
-
} else if (explicitPack === "auto") {
|
|
869
|
-
const pages = parsed?.pages || [];
|
|
870
|
-
const landscapeCount = pages.filter((p) => p.isLandscape).length;
|
|
871
|
-
const portraitCount = pages.length - landscapeCount;
|
|
872
|
-
if (pages.length > 0 && portraitCount >= landscapeCount) {
|
|
873
|
-
pack = mergePacks(
|
|
874
|
-
resolveEffectivePack("business-brief", packs, fileConfig),
|
|
875
|
-
resolveEffectivePack("deck-and-ui", packs, fileConfig)
|
|
876
|
-
);
|
|
877
|
-
effectivePack = "business-brief+deck-and-ui";
|
|
878
|
-
packSource = "auto-pdf-portrait";
|
|
879
|
-
} else {
|
|
880
|
-
pack = resolveEffectivePack("deck-and-ui", packs, fileConfig);
|
|
881
|
-
effectivePack = "deck-and-ui";
|
|
882
|
-
packSource = "auto-pdf-landscape";
|
|
883
|
-
}
|
|
884
|
-
} else {
|
|
885
|
-
const packId = pickPackForFile(rel, modality, explicitPack, fileConfig);
|
|
886
|
-
pack = resolveEffectivePack(packId, packs, fileConfig);
|
|
887
|
-
effectivePack = packId;
|
|
888
|
-
packSource = fileConfig.pack ? "config" : "default-modality";
|
|
889
|
-
}
|
|
890
|
-
const res = auditPdfDocument(parsed, { filename: rel, pack, config: fileConfig, register });
|
|
891
|
-
const uninspectable = res.skipped.some((s) => s.file === rel);
|
|
892
|
-
return {
|
|
893
|
-
checked: !uninspectable,
|
|
894
|
-
findings: res.findings,
|
|
895
|
-
unusedSuppressions: [],
|
|
896
|
-
coverageWarnings: res.coverageWarnings || [],
|
|
897
|
-
skipped: res.skipped,
|
|
898
|
-
effectivePack,
|
|
899
|
-
packSource,
|
|
900
|
-
rulesetHash: computeRulesetHash(pack),
|
|
901
|
-
register: regInfo.register,
|
|
902
|
-
registerSource: regInfo.registerSource,
|
|
903
|
-
};
|
|
904
|
-
} catch (err) {
|
|
905
|
-
return {
|
|
906
|
-
checked: false,
|
|
907
|
-
findings: [],
|
|
908
|
-
unusedSuppressions: [],
|
|
909
|
-
coverageWarnings: [],
|
|
910
|
-
skipped: [{ file: rel, reason: `Uninspectable PDF: ${err.message}` }],
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
let text;
|
|
916
|
-
try {
|
|
917
|
-
text = decodeUtf8Strict(buf);
|
|
918
|
-
} catch {
|
|
919
|
-
return {
|
|
920
|
-
checked: false,
|
|
921
|
-
findings: [],
|
|
922
|
-
unusedSuppressions: [],
|
|
923
|
-
coverageWarnings: [],
|
|
924
|
-
skipped: [{ file: rel, reason: "Non-UTF-8 text encoding; convert to UTF-8 to inspect" }],
|
|
925
|
-
};
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
const { pack, effectivePack, packSource } = resolveTextPackAndSource(text, rel, modality, explicitPack, fileConfig, packs);
|
|
929
|
-
const regInfo = resolveRegister(text, { filename: rel, flagRegister: register, config: fileConfig });
|
|
930
|
-
|
|
931
|
-
const res = auditText(text, { filename: rel, modality, pack, config: fileConfig, register });
|
|
932
|
-
let findings = res.findings;
|
|
933
|
-
if (includePatterns) {
|
|
934
|
-
const patRes = auditPatterns(text, { filename: rel, modality, banks: banks || loadPatternBanks(), config: fileConfig });
|
|
935
|
-
findings = mergePatternBankFindings(findings, patRes.findings, { packs, pack, register: regInfo.register, config: fileConfig });
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
let profileObj = null;
|
|
939
|
-
let mlInput = null;
|
|
940
|
-
if (PROSE_ML_MODALITIES.has(modality) && (includeMl || includeProfile || text.length >= 2000 || modality === "html")) {
|
|
941
|
-
profileObj = analyzeTextProfile(text, { modality, config: fileConfig });
|
|
942
|
-
if (includeMl) {
|
|
943
|
-
mlInput = modality === "html" || modality === "svg" ? buildZones(text, modality, fileConfig).prose : text;
|
|
944
|
-
const mlRes = buildPocketMlFindings(mlInput, rel, findings, null, { profile: profileObj, modality, register: regInfo.register });
|
|
945
|
-
findings = [...findings, ...mlRes.findings];
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
const coverageWarnings = collectTextCoverageWarnings(text, modality, rel, profileObj);
|
|
950
|
-
let profileItem = null;
|
|
951
|
-
if (includeProfile && PROSE_ML_MODALITIES.has(modality)) {
|
|
952
|
-
const pocketSrc = mlInput ?? (modality === "html" || modality === "svg" ? buildZones(text, modality, fileConfig).prose : text);
|
|
953
|
-
profileItem = {
|
|
954
|
-
file: rel,
|
|
955
|
-
profile: profileObj || analyzeTextProfile(text, { modality, config: fileConfig }),
|
|
956
|
-
pocketModel: summarizePocketForProfile(pocketSrc),
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
return {
|
|
961
|
-
checked: true,
|
|
962
|
-
findings,
|
|
963
|
-
unusedSuppressions: res.unusedSuppressions,
|
|
964
|
-
coverageWarnings,
|
|
965
|
-
skipped: [],
|
|
966
|
-
effectivePack,
|
|
967
|
-
packSource,
|
|
968
|
-
rulesetHash: computeRulesetHash(pack),
|
|
969
|
-
register: regInfo.register,
|
|
970
|
-
registerSource: regInfo.registerSource,
|
|
971
|
-
profileItem,
|
|
972
|
-
_cpLineStarts: buildCodepointLineStarts(text),
|
|
973
|
-
};
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
// ---------- Subcommands ----------
|
|
977
|
-
|
|
978
|
-
const COMMAND_SPECS = {
|
|
979
|
-
check: {
|
|
980
|
-
bools: ["json", "staged", "report-unused", "profile", "ml", "patterns", "deep", "compact", "quiet", "help", "version"],
|
|
981
|
-
strings: ["pack", "register", "config", "fail-on", "format", "changed", "stdin-filename", "lang", "rule"],
|
|
982
|
-
optionalStrings: ["changed"],
|
|
983
|
-
shortBools: { q: "quiet", h: "help", v: "version" },
|
|
984
|
-
shortStrings: {},
|
|
985
|
-
usage:
|
|
986
|
-
"dislop check [paths... | -] [--pack <id|auto>] [--register <id|auto>] [--deep] [--compact] [--profile] [--ml] [--patterns]\n" +
|
|
987
|
-
" [--fail-on error|warning|info|never] [--format text|json|agent|sarif|github|md]\n" +
|
|
988
|
-
" [--changed [ref] | --staged] [--rule <id,...>] [--stdin-filename <name>]\n" +
|
|
989
|
-
" [--report-unused] [--config <path>] [-q|--quiet] [--lang en|zh]",
|
|
990
|
-
summary: "Audit files, directories, or stdin for AI artifacts, clichés, and template layouts (0 network calls).",
|
|
991
|
-
examples: [
|
|
992
|
-
"dislop check .",
|
|
993
|
-
"dislop check draft.md --deep --lang zh",
|
|
994
|
-
"dislop check draft.md --register argumentative --format agent",
|
|
995
|
-
"dislop check --changed=origin/main --format github",
|
|
996
|
-
],
|
|
997
|
-
},
|
|
998
|
-
verify: {
|
|
999
|
-
bools: ["allow-added", "strict", "staged", "json", "help", "version"],
|
|
1000
|
-
strings: ["pack", "register", "git", "keep", "format", "lang", "stdin-filename", "config"],
|
|
1001
|
-
optionalStrings: ["git"],
|
|
1002
|
-
shortBools: { h: "help", v: "version" },
|
|
1003
|
-
shortStrings: {},
|
|
1004
|
-
usage: "dislop verify (<before> <after> | --git [ref] <file>) [--keep a,b] [--pack <id|auto>] [--register <name>] [--allow-added] [--strict] [--lang en|zh] [--json]",
|
|
1005
|
-
summary: "Verify a revised draft retains numbers, qualifiers, keep terms, and introduces zero new AI slop.",
|
|
1006
|
-
examples: [
|
|
1007
|
-
"dislop verify --git HEAD draft.md",
|
|
1008
|
-
"dislop verify before.md after.md --keep latency,SLA --strict --json",
|
|
1009
|
-
],
|
|
1010
|
-
},
|
|
1011
|
-
explain: {
|
|
1012
|
-
bools: ["json", "help", "version"],
|
|
1013
|
-
strings: ["lang", "format"],
|
|
1014
|
-
optionalStrings: [],
|
|
1015
|
-
shortBools: { h: "help", v: "version" },
|
|
1016
|
-
shortStrings: {},
|
|
1017
|
-
usage: "dislop explain <rule-id> [--lang en|zh] [--format text|json] [--json]",
|
|
1018
|
-
summary: "Show rationale, deletion test, and bad/trap/good examples for a rule or pattern ID.",
|
|
1019
|
-
examples: ["dislop explain negation-pivot-frame --lang zh", "dislop explain chatbot-artifact --json"],
|
|
1020
|
-
},
|
|
1021
|
-
packs: {
|
|
1022
|
-
bools: ["json", "help", "version"],
|
|
1023
|
-
strings: ["format"],
|
|
1024
|
-
optionalStrings: [],
|
|
1025
|
-
shortBools: { h: "help", v: "version" },
|
|
1026
|
-
shortStrings: {},
|
|
1027
|
-
usage: "dislop packs [--format text|json] [--json]",
|
|
1028
|
-
summary: "List bundled rule packs and supported file types.",
|
|
1029
|
-
examples: ["dislop packs", "dislop packs --json"],
|
|
1030
|
-
},
|
|
1031
|
-
catalog: {
|
|
1032
|
-
bools: ["json", "no-exemplars", "help", "version"],
|
|
1033
|
-
strings: ["query", "pack", "category", "dimension", "family", "modality", "severity", "tier", "lang", "format", "limit"],
|
|
1034
|
-
optionalStrings: [],
|
|
1035
|
-
shortBools: { h: "help", v: "version" },
|
|
1036
|
-
shortStrings: {},
|
|
1037
|
-
usage:
|
|
1038
|
-
"dislop catalog [query] [--pack <id>] [--category <cat>] [--dimension <dim>] [--family <prefix>]\n" +
|
|
1039
|
-
" [--modality <mod>] [--severity <sev>] [--tier invariant|taste] [--limit <n>]\n" +
|
|
1040
|
-
" [--no-exemplars] [--format text|json|md] [--lang en|zh]",
|
|
1041
|
-
summary: "Search and filter dislop's 53-rule AI-slop catalog.",
|
|
1042
|
-
examples: ["dislop catalog negation --lang zh", "dislop catalog --pack deck-and-ui --format md"],
|
|
1043
|
-
},
|
|
1044
|
-
patterns: {
|
|
1045
|
-
bools: ["json", "help", "version"],
|
|
1046
|
-
strings: ["stdin-filename", "angle", "lang", "format"],
|
|
1047
|
-
optionalStrings: [],
|
|
1048
|
-
shortBools: { h: "help", v: "version" },
|
|
1049
|
-
shortStrings: {},
|
|
1050
|
-
usage: "dislop patterns [file | -] [--stdin-filename <name>] [--angle <a,b>] [--lang en|zh] [--json]",
|
|
1051
|
-
summary: "Run multi-angle extended pattern-bank scan and profile.",
|
|
1052
|
-
examples: ["dislop patterns draft.md --lang zh", "cat draft.md | dislop patterns - --json"],
|
|
1053
|
-
},
|
|
1054
|
-
voice: {
|
|
1055
|
-
bools: ["json", "help", "version"],
|
|
1056
|
-
strings: ["output", "lang", "format"],
|
|
1057
|
-
optionalStrings: [],
|
|
1058
|
-
shortBools: { h: "help", v: "version" },
|
|
1059
|
-
shortStrings: { o: "output" },
|
|
1060
|
-
usage: "dislop voice [paths... | -] [--output|-o <voice.json>] [--lang auto|en|zh] [--json]",
|
|
1061
|
-
summary: "Extract an offline deterministic dislop.voice/1 writing profile (0 network calls).",
|
|
1062
|
-
examples: ["dislop voice notes/*.md -o voice.json", "dislop voice essays.md --lang zh --json"],
|
|
1063
|
-
},
|
|
1064
|
-
model: {
|
|
1065
|
-
bools: ["force", "dry-run", "yes", "no-copy", "allow-lan", "no-loopback", "json", "help", "version"],
|
|
1066
|
-
strings: ["tier", "provider", "sha256", "cache-dir", "threshold", "stdin-filename", "pack", "config", "endpoint", "model", "output", "format", "lang"],
|
|
1067
|
-
optionalStrings: [],
|
|
1068
|
-
shortBools: { h: "help", v: "version" },
|
|
1069
|
-
shortStrings: { o: "output" },
|
|
1070
|
-
usage: "dislop model [status|score|install|import|remove|deslop] [target] [--tier <t>] [--lang en|zh] [--json]",
|
|
1071
|
-
summary: "Inspect bundled 14.6 KB Pocket ML, hardware fit, and manage optional local models.",
|
|
1072
|
-
examples: ["dislop model status --lang zh", "dislop model score draft.md --json"],
|
|
1073
|
-
},
|
|
1074
|
-
setup: {
|
|
1075
|
-
bools: ["force", "dry-run", "yes", "json", "help", "version"],
|
|
1076
|
-
strings: ["tier", "provider", "cache-dir", "format", "lang"],
|
|
1077
|
-
optionalStrings: [],
|
|
1078
|
-
shortBools: { h: "help", v: "version" },
|
|
1079
|
-
shortStrings: {},
|
|
1080
|
-
usage: "dislop setup [--tier auto|none|fast|balanced|quality] [--dry-run] [--force] [--lang en|zh]",
|
|
1081
|
-
summary: "Interactive or flag-driven optional local GGUF model setup.",
|
|
1082
|
-
examples: ["dislop setup --dry-run", "dislop setup --tier fast --yes"],
|
|
1083
|
-
},
|
|
1084
|
-
deslop: {
|
|
1085
|
-
bools: ["local", "allow-lan", "json", "help", "version"],
|
|
1086
|
-
strings: ["pack", "register", "config", "stdin-filename", "endpoint", "model", "output", "format", "lang"],
|
|
1087
|
-
optionalStrings: [],
|
|
1088
|
-
shortBools: { h: "help", v: "version" },
|
|
1089
|
-
shortStrings: { o: "output" },
|
|
1090
|
-
usage: "dislop deslop [file | -] --local [--pack <id|auto>] [--register <name>] [--endpoint <url>] [--model <id>] [--output|-o <file>] [--json]",
|
|
1091
|
-
summary: "Fact-locked paragraph cleanup using a local loopback model (--local).",
|
|
1092
|
-
examples: ["dislop deslop draft.md --local -o clean.md"],
|
|
1093
|
-
},
|
|
1094
|
-
resources: {
|
|
1095
|
-
bools: ["json", "help", "version"],
|
|
1096
|
-
strings: ["format"],
|
|
1097
|
-
optionalStrings: [],
|
|
1098
|
-
shortBools: { h: "help", v: "version" },
|
|
1099
|
-
shortStrings: {},
|
|
1100
|
-
usage: "dislop resources [--format text|json] [--json]",
|
|
1101
|
-
summary: "Show bundled offline packs, static agent links, and Official Cloud MCP details.",
|
|
1102
|
-
examples: ["dislop resources", "dislop resources --json"],
|
|
1103
|
-
},
|
|
1104
|
-
"pack-test": {
|
|
1105
|
-
bools: ["help", "version"],
|
|
1106
|
-
strings: [],
|
|
1107
|
-
optionalStrings: [],
|
|
1108
|
-
shortBools: { h: "help", v: "version" },
|
|
1109
|
-
shortStrings: {},
|
|
1110
|
-
usage: "dislop pack-test",
|
|
1111
|
-
summary: "Validate Pack Schema v2 manifests and embedded hit/clean fixture assertions.",
|
|
1112
|
-
examples: ["dislop pack-test"],
|
|
1113
|
-
},
|
|
1114
|
-
init: {
|
|
1115
|
-
bools: ["help", "version"],
|
|
1116
|
-
strings: [],
|
|
1117
|
-
optionalStrings: [],
|
|
1118
|
-
shortBools: { h: "help", v: "version" },
|
|
1119
|
-
shortStrings: {},
|
|
1120
|
-
usage: "dislop init",
|
|
1121
|
-
summary: "Create starter .dislop.json config and ensure .dislop.local.json is gitignored.",
|
|
1122
|
-
examples: ["dislop init"],
|
|
1123
|
-
},
|
|
1124
|
-
apply: {
|
|
1125
|
-
bools: ["all", "help"],
|
|
1126
|
-
strings: ["review-file", "source-file", "include", "exclude"],
|
|
1127
|
-
optionalStrings: [],
|
|
1128
|
-
shortBools: { h: "help" },
|
|
1129
|
-
shortStrings: {},
|
|
1130
|
-
usage: "dislop apply --review-file REPORT --source-file FILE (--include IDS | --all [--exclude IDS])",
|
|
1131
|
-
summary: "Apply selected exact edits from a saved JSON review.",
|
|
1132
|
-
examples: ["dislop apply --review-file review.json --source-file draft.md --include 2,5"],
|
|
1133
|
-
},
|
|
1134
|
-
review: {
|
|
1135
|
-
bools: ["interactive-apply", "offline", "compact", "dry-run", "print-prompt", "yes", "include-notes", "include-hidden", "json", "help", "version"],
|
|
1136
|
-
strings: ["endpoint", "api-key-env", "provider", "model", "base-url", "pack", "register", "format", "lang", "fail-on", "timeout", "max-chunks", "stdin-filename", "config"],
|
|
1137
|
-
optionalStrings: [],
|
|
1138
|
-
shortBools: { y: "yes", h: "help", v: "version" },
|
|
1139
|
-
shortStrings: {},
|
|
1140
|
-
usage:
|
|
1141
|
-
"dislop review [file | -] [--offline | --endpoint <url> | --provider openai|gemini|openrouter|compatible|local]\n" +
|
|
1142
|
-
" [--model <id>] [--base-url <url>] [--pack <id|auto>] [--register <id|auto>]\n" +
|
|
1143
|
-
" [--interactive-apply] [--dry-run] [--print-prompt] [--yes] [--format text|json|agent] [--lang en|zh]",
|
|
1144
|
-
summary: "Multi-layer editorial review (offline rubric preflight or explicit opt-in BYOK LLM review).",
|
|
1145
|
-
examples: [
|
|
1146
|
-
"dislop review draft.md --offline --lang zh",
|
|
1147
|
-
"dislop review draft.md --provider openai --dry-run",
|
|
1148
|
-
"dislop review draft.md --provider gemini --model gemini-3.1-flash-lite-preview --yes",
|
|
1149
|
-
],
|
|
1150
|
-
},
|
|
1151
|
-
doctor: {
|
|
1152
|
-
bools: ["online", "no-loopback", "json", "help", "version"],
|
|
1153
|
-
strings: ["cache-dir", "format", "lang"],
|
|
1154
|
-
optionalStrings: [],
|
|
1155
|
-
shortBools: { h: "help", v: "version" },
|
|
1156
|
-
shortStrings: {},
|
|
1157
|
-
usage: "dislop doctor [--online] [--no-loopback] [--lang en|zh] [--json]",
|
|
1158
|
-
summary: "Check 3-layer readiness (Skill, Local CLI + Pocket ML + local runners, BYOK review env, and optional --online Cloud MCP ping).",
|
|
1159
|
-
examples: ["dislop doctor", "dislop doctor --lang zh --json", "dislop doctor --online"],
|
|
1160
|
-
},
|
|
1161
|
-
};
|
|
1162
|
-
COMMAND_SPECS.search = COMMAND_SPECS.catalog;
|
|
1163
|
-
|
|
1164
|
-
function levenshtein(a, b) {
|
|
1165
|
-
const m = a.length;
|
|
1166
|
-
const n = b.length;
|
|
1167
|
-
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
|
1168
|
-
for (let i = 0; i <= m; i += 1) dp[i][0] = i;
|
|
1169
|
-
for (let j = 0; j <= n; j += 1) dp[0][j] = j;
|
|
1170
|
-
for (let i = 1; i <= m; i += 1) {
|
|
1171
|
-
for (let j = 1; j <= n; j += 1) {
|
|
1172
|
-
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
1173
|
-
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
return dp[m][n];
|
|
1177
|
-
}
|
|
1178
|
-
|
|
1179
|
-
function closestFlagSuggestion(unknown, knownFlags) {
|
|
1180
|
-
let best = null;
|
|
1181
|
-
let bestDist = 4;
|
|
1182
|
-
for (const cand of knownFlags) {
|
|
1183
|
-
const d = levenshtein(unknown, cand);
|
|
1184
|
-
if (d < bestDist) {
|
|
1185
|
-
bestDist = d;
|
|
1186
|
-
best = cand;
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
1189
|
-
return best ? ` Did you mean '--${best}'?` : "";
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
function printSubcommandHelp(cmdName) {
|
|
1193
|
-
const spec = COMMAND_SPECS[cmdName];
|
|
1194
|
-
if (!spec) {
|
|
1195
|
-
printHelp();
|
|
1196
|
-
return;
|
|
1197
|
-
}
|
|
1198
|
-
console.log(`dislop ${cmdName} — ${spec.summary}\n`);
|
|
1199
|
-
console.log(`Usage:\n ${spec.usage}`);
|
|
1200
|
-
if (spec.examples?.length) {
|
|
1201
|
-
console.log(`\nExamples:\n${spec.examples.map((ex) => ` ${ex}`).join("\n")}`);
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
function shouldUseColor() {
|
|
1206
|
-
if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== "0") return true;
|
|
1207
|
-
if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== "") return false;
|
|
1208
|
-
return Boolean(process.stdout.isTTY);
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
function colorizeTextReport(text, useColor) {
|
|
1212
|
-
if (!useColor || !text) return text;
|
|
1213
|
-
const RESET = "\x1b[0m";
|
|
1214
|
-
const RED = "\x1b[31m";
|
|
1215
|
-
const YELLOW = "\x1b[33m";
|
|
1216
|
-
const CYAN = "\x1b[36m";
|
|
1217
|
-
const DIM = "\x1b[2m";
|
|
1218
|
-
const GREEN = "\x1b[32m";
|
|
1219
|
-
return text
|
|
1220
|
-
.split("\n")
|
|
1221
|
-
.map((line) => {
|
|
1222
|
-
if (line.startsWith(" [ERROR]") || line.startsWith(" [硬伤]")) {
|
|
1223
|
-
return line.replace(/^(\s*\[(?:ERROR|硬伤)\])/, `${RED}$1${RESET}`);
|
|
1224
|
-
}
|
|
1225
|
-
if (line.startsWith(" [WARNING]") || line.startsWith(" [提醒]")) {
|
|
1226
|
-
return line.replace(/^(\s*\[(?:WARNING|提醒)\])/, `${YELLOW}$1${RESET}`);
|
|
1227
|
-
}
|
|
1228
|
-
if (line.startsWith(" [INFO]") || line.startsWith(" [提示]")) {
|
|
1229
|
-
return line.replace(/^(\s*\[(?:INFO|提示)\])/, `${CYAN}$1${RESET}`);
|
|
1230
|
-
}
|
|
1231
|
-
if (
|
|
1232
|
-
line.startsWith(" [SKIP]") ||
|
|
1233
|
-
line.startsWith(" [跳过]") ||
|
|
1234
|
-
line.startsWith(" [UNUSED]") ||
|
|
1235
|
-
line.startsWith(" [失效豁免]") ||
|
|
1236
|
-
line.startsWith(" [COVERAGE]") ||
|
|
1237
|
-
line.startsWith(" [覆盖提示]")
|
|
1238
|
-
) {
|
|
1239
|
-
return `${DIM}${line}${RESET}`;
|
|
1240
|
-
}
|
|
1241
|
-
if (line.startsWith("dislop: no known patterns found") || line.startsWith("dislop: 未发现已知模式")) {
|
|
1242
|
-
return `${GREEN}${line}${RESET}`;
|
|
1243
|
-
}
|
|
1244
|
-
return line;
|
|
1245
|
-
})
|
|
1246
|
-
.join("\n");
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
function parseFlags(args, cmdName = null) {
|
|
1250
|
-
const spec = cmdName ? COMMAND_SPECS[cmdName] : null;
|
|
1251
|
-
const boolSet = new Set(spec ? spec.bools : [
|
|
1252
|
-
"json", "staged", "report-unused", "no-loopback", "help", "version", "mcp",
|
|
1253
|
-
"no-exemplars", "profile", "ml", "patterns", "deep", "compact", "quiet", "force",
|
|
1254
|
-
"dry-run", "yes", "no-copy", "local", "allow-lan", "offline", "allow-added", "strict",
|
|
1255
|
-
]);
|
|
1256
|
-
const stringSet = spec ? new Set(spec.strings) : null;
|
|
1257
|
-
const optionalSet = new Set(spec ? spec.optionalStrings : ["changed", "git"]);
|
|
1258
|
-
const shortBools = spec ? spec.shortBools : { h: "help", v: "version", q: "quiet" };
|
|
1259
|
-
const shortStrings = spec ? spec.shortStrings : { o: "output" };
|
|
1260
|
-
const allKnown = spec ? [...spec.bools, ...spec.strings] : [];
|
|
1261
|
-
|
|
1262
|
-
for (const a of args) {
|
|
1263
|
-
if (a === "--") break;
|
|
1264
|
-
if (a === "-h" || a === "--help") {
|
|
1265
|
-
return { flags: { help: true }, positional: [] };
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
const flags = {};
|
|
1270
|
-
const positional = [];
|
|
1271
|
-
let endOfFlags = false;
|
|
1272
|
-
const cwd = process.cwd();
|
|
1273
|
-
|
|
1274
|
-
for (let i = 0; i < args.length; i += 1) {
|
|
1275
|
-
const arg = args[i];
|
|
1276
|
-
if (endOfFlags) {
|
|
1277
|
-
positional.push(arg);
|
|
1278
|
-
continue;
|
|
1279
|
-
}
|
|
1280
|
-
if (arg === "--") {
|
|
1281
|
-
endOfFlags = true;
|
|
1282
|
-
continue;
|
|
1283
|
-
}
|
|
1284
|
-
if (arg === "-") {
|
|
1285
|
-
positional.push("-");
|
|
1286
|
-
continue;
|
|
1287
|
-
}
|
|
1288
|
-
if (arg.startsWith("--")) {
|
|
1289
|
-
const eq = arg.indexOf("=");
|
|
1290
|
-
const key = eq !== -1 ? arg.slice(2, eq) : arg.slice(2);
|
|
1291
|
-
if (spec && !boolSet.has(key) && !stringSet.has(key)) {
|
|
1292
|
-
const hint = closestFlagSuggestion(key, allKnown);
|
|
1293
|
-
console.error(`dislop ${cmdName}: unknown flag '--${key}'.${hint} Run 'dislop ${cmdName} --help'.`);
|
|
1294
|
-
process.exit(2);
|
|
1295
|
-
}
|
|
1296
|
-
if (eq !== -1) {
|
|
1297
|
-
const val = arg.slice(eq + 1);
|
|
1298
|
-
if (boolSet.has(key)) {
|
|
1299
|
-
const low = val.trim().toLowerCase();
|
|
1300
|
-
if (low === "true" || low === "1" || low === "yes") flags[key] = true;
|
|
1301
|
-
else if (low === "false" || low === "0" || low === "no") flags[key] = false;
|
|
1302
|
-
else {
|
|
1303
|
-
console.error(`dislop: flag '--${key}' does not accept value '${val}'`);
|
|
1304
|
-
process.exit(2);
|
|
1305
|
-
}
|
|
1306
|
-
} else if (optionalSet.has(key) && val === "") {
|
|
1307
|
-
flags[key] = "HEAD";
|
|
1308
|
-
} else {
|
|
1309
|
-
flags[key] = val;
|
|
1310
|
-
}
|
|
1311
|
-
} else if (boolSet.has(key)) {
|
|
1312
|
-
flags[key] = true;
|
|
1313
|
-
} else if (optionalSet.has(key)) {
|
|
1314
|
-
const next = args[i + 1];
|
|
1315
|
-
if (i + 1 >= args.length || next === "-" || next.startsWith("-")) {
|
|
1316
|
-
flags[key] = "HEAD";
|
|
1317
|
-
} else if ((key === "changed" || key === "git") && fs.existsSync(path.resolve(cwd, next))) {
|
|
1318
|
-
flags[key] = "HEAD";
|
|
1319
|
-
} else {
|
|
1320
|
-
flags[key] = next;
|
|
1321
|
-
i += 1;
|
|
1322
|
-
}
|
|
1323
|
-
} else if (i + 1 < args.length) {
|
|
1324
|
-
const next = args[i + 1];
|
|
1325
|
-
if (next.length > 1 && next.startsWith("-")) {
|
|
1326
|
-
console.error(`dislop: flag '--${key}' requires a value (got '${next}')`);
|
|
1327
|
-
process.exit(2);
|
|
1328
|
-
}
|
|
1329
|
-
flags[key] = next;
|
|
1330
|
-
i += 1;
|
|
1331
|
-
} else {
|
|
1332
|
-
console.error(`dislop: flag '--${key}' requires a value`);
|
|
1333
|
-
process.exit(2);
|
|
1334
|
-
}
|
|
1335
|
-
} else if (arg.startsWith("-") && arg.length > 1) {
|
|
1336
|
-
const eq = arg.indexOf("=");
|
|
1337
|
-
const shortKey = eq !== -1 ? arg.slice(1, eq) : arg.slice(1);
|
|
1338
|
-
if (shortBools[shortKey] && eq === -1) {
|
|
1339
|
-
flags[shortBools[shortKey]] = true;
|
|
1340
|
-
} else if (shortStrings[shortKey]) {
|
|
1341
|
-
if (eq !== -1) {
|
|
1342
|
-
flags[shortStrings[shortKey]] = arg.slice(eq + 1);
|
|
1343
|
-
} else if (i + 1 < args.length) {
|
|
1344
|
-
const next = args[i + 1];
|
|
1345
|
-
if (next.length > 1 && next.startsWith("-")) {
|
|
1346
|
-
console.error(`dislop: flag '-${shortKey}' requires a value (got '${next}')`);
|
|
1347
|
-
process.exit(2);
|
|
1348
|
-
}
|
|
1349
|
-
flags[shortStrings[shortKey]] = next;
|
|
1350
|
-
i += 1;
|
|
1351
|
-
} else {
|
|
1352
|
-
console.error(`dislop: flag '-${shortKey}' requires a value`);
|
|
1353
|
-
process.exit(2);
|
|
1354
|
-
}
|
|
1355
|
-
} else if (shortKey.length > 1 && eq === -1 && [...shortKey].every((ch) => shortBools[ch])) {
|
|
1356
|
-
for (const ch of shortKey) flags[shortBools[ch]] = true;
|
|
1357
|
-
} else {
|
|
1358
|
-
console.error(`dislop${cmdName ? ` ${cmdName}` : ""}: unknown flag '${arg}'. Run 'dislop${cmdName ? ` ${cmdName}` : ""} --help'.`);
|
|
1359
|
-
process.exit(2);
|
|
1360
|
-
}
|
|
1361
|
-
} else {
|
|
1362
|
-
positional.push(arg);
|
|
1363
|
-
}
|
|
1364
|
-
}
|
|
1365
|
-
if (!spec && flags.help) {
|
|
1366
|
-
printHelp();
|
|
1367
|
-
process.exit(0);
|
|
1368
|
-
}
|
|
1369
|
-
return { flags, positional };
|
|
1370
|
-
}
|
|
1371
|
-
|
|
1372
|
-
function readStdinTextChecked(cmdLabel = "check") {
|
|
1373
|
-
const buf = fs.readFileSync(0);
|
|
1374
|
-
if (buf.length >= 4 && buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04) {
|
|
1375
|
-
console.error(`dislop ${cmdLabel}: stdin looks like binary ZIP/OOXML (.docx/.pptx); pass the file path instead (e.g., 'dislop ${cmdLabel} deck.pptx').`);
|
|
1376
|
-
process.exit(2);
|
|
1377
|
-
}
|
|
1378
|
-
try {
|
|
1379
|
-
return decodeUtf8Strict(buf);
|
|
1380
|
-
} catch {
|
|
1381
|
-
console.error(`dislop ${cmdLabel}: stdin is not valid UTF-8 text; convert to UTF-8 or pass a supported file path.`);
|
|
1382
|
-
process.exit(2);
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
function detectStdinFilename(rawText, explicitName) {
|
|
1387
|
-
if (explicitName) return explicitName;
|
|
1388
|
-
const head = String(rawText || "").replace(/^\ufeff/, "").trimStart().slice(0, 128).toLowerCase();
|
|
1389
|
-
if (head.startsWith("<!doctype html") || head.startsWith("<html")) {
|
|
1390
|
-
return "stdin.html";
|
|
1391
|
-
}
|
|
1392
|
-
return "stdin.md";
|
|
1393
|
-
}
|
|
1394
|
-
|
|
1395
|
-
function collectKnownRuleIds(packs, banks = null) {
|
|
1396
|
-
const known = new Set(["pocket-stealth-vapor"]);
|
|
1397
|
-
for (const p of Object.values(packs || {})) {
|
|
1398
|
-
for (const r of p.rules || []) {
|
|
1399
|
-
if (r.id) known.add(r.id);
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
const loadedBanks = banks || loadPatternBanks();
|
|
1403
|
-
for (const bank of Object.values(loadedBanks || {})) {
|
|
1404
|
-
for (const pat of bank.patterns || []) {
|
|
1405
|
-
if (pat.ruleId) known.add(pat.ruleId);
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
const patLib = loadPatternLibrary();
|
|
1409
|
-
for (const rid of Object.keys(patLib)) known.add(rid);
|
|
1410
|
-
return known;
|
|
1411
|
-
}
|
|
1412
|
-
|
|
1413
|
-
function assertTextOrJsonFormat(format) {
|
|
1414
|
-
if (!["text", "json"].includes(format)) {
|
|
1415
|
-
console.error(`dislop: invalid --format '${format}' (expected text or json)`);
|
|
1416
|
-
process.exit(2);
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
function applyCompactReport(report) {
|
|
1421
|
-
const ruleMeta = {};
|
|
1422
|
-
const compactFindings = [];
|
|
1423
|
-
for (const f of report.findings || []) {
|
|
1424
|
-
const rid = f.ruleId;
|
|
1425
|
-
const strategy = f.fixStrategy || deriveFixStrategy({ id: rid, family: f.family });
|
|
1426
|
-
if (!ruleMeta[rid]) {
|
|
1427
|
-
ruleMeta[rid] = {
|
|
1428
|
-
tier: f.tier || "taste",
|
|
1429
|
-
family: f.family || "general",
|
|
1430
|
-
fixStrategy: strategy,
|
|
1431
|
-
message: f.message,
|
|
1432
|
-
...(f.deletionTest ? { deletionTest: f.deletionTest } : {}),
|
|
1433
|
-
};
|
|
1434
|
-
}
|
|
1435
|
-
compactFindings.push({
|
|
1436
|
-
fingerprint: f.fingerprint,
|
|
1437
|
-
ruleId: rid,
|
|
1438
|
-
severity: f.severity,
|
|
1439
|
-
fixStrategy: strategy,
|
|
1440
|
-
file: f.file,
|
|
1441
|
-
modality: f.modality,
|
|
1442
|
-
location: f.location,
|
|
1443
|
-
line: f.line,
|
|
1444
|
-
col: f.col,
|
|
1445
|
-
...(f.span ? { span: f.span } : {}),
|
|
1446
|
-
match: f.match,
|
|
1447
|
-
});
|
|
1448
|
-
}
|
|
1449
|
-
return {
|
|
1450
|
-
...report,
|
|
1451
|
-
compact: true,
|
|
1452
|
-
ruleMeta,
|
|
1453
|
-
findings: compactFindings,
|
|
1454
|
-
};
|
|
1455
|
-
}
|
|
1456
|
-
|
|
1457
|
-
function runCheck(args, packs) {
|
|
1458
|
-
const { flags, positional } = parseFlags(args, "check");
|
|
1459
|
-
if (flags.help) {
|
|
1460
|
-
printSubcommandHelp("check");
|
|
1461
|
-
return;
|
|
1462
|
-
}
|
|
1463
|
-
const cwd = process.cwd();
|
|
1464
|
-
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
1465
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
1466
|
-
const failOn = flags["fail-on"] || config.failOn || "error";
|
|
1467
|
-
const lang = flags.lang || "en";
|
|
1468
|
-
if (!["en", "zh"].includes(lang)) {
|
|
1469
|
-
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
1470
|
-
process.exit(2);
|
|
1471
|
-
}
|
|
1472
|
-
const reportUnused = Boolean(flags["report-unused"]);
|
|
1473
|
-
const quiet = Boolean(flags.quiet);
|
|
1474
|
-
const useColor = format === "text" && shouldUseColor();
|
|
1475
|
-
const includeProfile = Boolean(flags.profile || flags.deep);
|
|
1476
|
-
const includeMl = Boolean(flags.ml || flags.deep);
|
|
1477
|
-
const includePatterns = Boolean(flags.patterns || flags.deep);
|
|
1478
|
-
const compactJson = Boolean(flags.compact && format === "json");
|
|
1479
|
-
const banks = includePatterns ? loadPatternBanks() : null;
|
|
1480
|
-
|
|
1481
|
-
const validFormats = new Set(["text", "json", "agent", "sarif", "github", "md"]);
|
|
1482
|
-
if (!validFormats.has(format)) {
|
|
1483
|
-
console.error(`dislop: invalid --format '${format}' (expected text, json, agent, sarif, github, or md)`);
|
|
1484
|
-
process.exit(2);
|
|
1485
|
-
}
|
|
1486
|
-
if (!SEVERITY_RANK[failOn]) {
|
|
1487
|
-
console.error(`dislop: invalid --fail-on '${failOn}' (expected error, warning, info, or never)`);
|
|
1488
|
-
process.exit(2);
|
|
1489
|
-
}
|
|
1490
|
-
|
|
1491
|
-
let flagRegister = null;
|
|
1492
|
-
if (flags.register !== undefined) {
|
|
1493
|
-
const norm = String(flags.register).trim().toLowerCase();
|
|
1494
|
-
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
1495
|
-
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
1496
|
-
process.exit(2);
|
|
1497
|
-
}
|
|
1498
|
-
flagRegister = norm;
|
|
1499
|
-
}
|
|
1500
|
-
|
|
1501
|
-
let ruleFilter = null;
|
|
1502
|
-
if (flags.rule !== undefined) {
|
|
1503
|
-
const requested = String(flags.rule)
|
|
1504
|
-
.split(",")
|
|
1505
|
-
.map((s) => s.trim())
|
|
1506
|
-
.filter(Boolean);
|
|
1507
|
-
if (requested.length === 0) {
|
|
1508
|
-
console.error("dislop check: '--rule' requires at least one rule ID");
|
|
1509
|
-
process.exit(2);
|
|
1510
|
-
}
|
|
1511
|
-
const known = collectKnownRuleIds(packs, banks);
|
|
1512
|
-
const unknown = requested.filter((r) => !known.has(r));
|
|
1513
|
-
if (unknown.length > 0) {
|
|
1514
|
-
console.error(`dislop check: unknown rule ID(s): ${unknown.join(", ")}. Run 'dislop catalog' to list valid rule IDs.`);
|
|
1515
|
-
process.exit(2);
|
|
1516
|
-
}
|
|
1517
|
-
ruleFilter = new Set(requested);
|
|
1518
|
-
}
|
|
1519
|
-
|
|
1520
|
-
if (flags.pack && flags.pack !== "auto" && !packs[flags.pack]) {
|
|
1521
|
-
console.error(`dislop: unknown pack '${flags.pack}' (available: auto, ${Object.keys(packs).join(", ")})`);
|
|
1522
|
-
process.exit(2);
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
// Stdin mode
|
|
1526
|
-
if (positional.includes("-")) {
|
|
1527
|
-
const stdinText = readStdinTextChecked("check");
|
|
1528
|
-
const filename = detectStdinFilename(stdinText, flags["stdin-filename"]);
|
|
1529
|
-
const modality = detectModality(filename) || "markdown";
|
|
1530
|
-
const fileConfig = resolveConfigForFile(filename, config);
|
|
1531
|
-
let resolved;
|
|
1532
|
-
let regInfo;
|
|
1533
|
-
try {
|
|
1534
|
-
resolved = resolveTextPackAndSource(stdinText, filename, modality, flags.pack || null, fileConfig, packs);
|
|
1535
|
-
regInfo = resolveRegister(stdinText, { filename, flagRegister, config: fileConfig });
|
|
1536
|
-
} catch (err) {
|
|
1537
|
-
console.error(`dislop: ${err.message}`);
|
|
1538
|
-
process.exit(2);
|
|
1539
|
-
}
|
|
1540
|
-
const { pack, effectivePack, packSource } = resolved;
|
|
1541
|
-
const res = auditText(stdinText, { filename, modality, pack, config: fileConfig, register: flagRegister });
|
|
1542
|
-
let findings = res.findings;
|
|
1543
|
-
if (includePatterns) {
|
|
1544
|
-
const patRes = auditPatterns(stdinText, { filename, modality, banks, config: fileConfig });
|
|
1545
|
-
findings = mergePatternBankFindings(findings, patRes.findings, {
|
|
1546
|
-
packs,
|
|
1547
|
-
pack,
|
|
1548
|
-
register: regInfo.register,
|
|
1549
|
-
config: fileConfig,
|
|
1550
|
-
});
|
|
1551
|
-
}
|
|
1552
|
-
let profileObj = null;
|
|
1553
|
-
let mlInput = null;
|
|
1554
|
-
if (PROSE_ML_MODALITIES.has(modality) && (includeMl || includeProfile || stdinText.length >= 2000 || modality === "html")) {
|
|
1555
|
-
profileObj = analyzeTextProfile(stdinText, { modality, config: fileConfig });
|
|
1556
|
-
if (includeMl) {
|
|
1557
|
-
mlInput = modality === "html" || modality === "svg" ? buildZones(stdinText, modality, fileConfig).prose : stdinText;
|
|
1558
|
-
findings = [
|
|
1559
|
-
...findings,
|
|
1560
|
-
...buildPocketMlFindings(mlInput, filename, findings, null, {
|
|
1561
|
-
profile: profileObj,
|
|
1562
|
-
modality,
|
|
1563
|
-
register: regInfo.register,
|
|
1564
|
-
}).findings,
|
|
1565
|
-
];
|
|
1566
|
-
}
|
|
1567
|
-
}
|
|
1568
|
-
if (ruleFilter) {
|
|
1569
|
-
findings = findings.filter((f) => ruleFilter.has(f.ruleId));
|
|
1570
|
-
}
|
|
1571
|
-
const triggered =
|
|
1572
|
-
findings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
|
|
1573
|
-
(reportUnused && res.unusedSuppressions.length > 0);
|
|
1574
|
-
const outFindings = quiet
|
|
1575
|
-
? findings.filter((f) => (SEVERITY_RANK[f.severity] || 1) >= SEVERITY_RANK[failOn])
|
|
1576
|
-
: findings;
|
|
1577
|
-
const coverageWarnings = collectTextCoverageWarnings(stdinText, modality, filename, profileObj);
|
|
1578
|
-
const pocketSrc = includeProfile && PROSE_ML_MODALITIES.has(modality)
|
|
1579
|
-
? mlInput ?? (modality === "html" || modality === "svg" ? buildZones(stdinText, modality, fileConfig).prose : stdinText)
|
|
1580
|
-
: null;
|
|
1581
|
-
const report = {
|
|
1582
|
-
version: ENGINE_VERSION,
|
|
1583
|
-
context: { register: regInfo.register, registerSource: regInfo.registerSource },
|
|
1584
|
-
rulesetHash: computeRulesetHash(pack),
|
|
1585
|
-
effectivePack,
|
|
1586
|
-
packSource,
|
|
1587
|
-
changedFilter: false,
|
|
1588
|
-
files: [{ file: filename, modality, effectivePack, packSource }],
|
|
1589
|
-
checkedCount: 1,
|
|
1590
|
-
skipped: [],
|
|
1591
|
-
coverageWarnings,
|
|
1592
|
-
findings: outFindings,
|
|
1593
|
-
unusedSuppressions: reportUnused ? res.unusedSuppressions : [],
|
|
1594
|
-
...(includeProfile && PROSE_ML_MODALITIES.has(modality)
|
|
1595
|
-
? {
|
|
1596
|
-
profiles: [
|
|
1597
|
-
{
|
|
1598
|
-
file: filename,
|
|
1599
|
-
profile: profileObj || analyzeTextProfile(stdinText, { modality, config: fileConfig }),
|
|
1600
|
-
pocketModel: summarizePocketForProfile(pocketSrc),
|
|
1601
|
-
},
|
|
1602
|
-
],
|
|
1603
|
-
}
|
|
1604
|
-
: {}),
|
|
1605
|
-
};
|
|
1606
|
-
const outReport = compactJson ? applyCompactReport(report) : report;
|
|
1607
|
-
const rendered = colorizeTextReport(formatReport(outReport, format, lang, { quiet, failOn }), useColor);
|
|
1608
|
-
if (rendered) console.log(rendered);
|
|
1609
|
-
if (useColor && !quiet && format === "text" && findings.length === 0 && (!reportUnused || res.unusedSuppressions.length === 0) && !includeMl && !includePatterns) {
|
|
1610
|
-
console.log(lang === "zh" ? " 提示: 可加 --deep 启用统计画像与内置隐蔽套话模型。" : " hint: run with --deep to enable rhythm telemetry and Pocket ML scoring.");
|
|
1611
|
-
}
|
|
1612
|
-
process.exitCode = triggered ? 1 : 0;
|
|
1613
|
-
return;
|
|
1614
|
-
}
|
|
1615
|
-
|
|
1616
|
-
let changedMap = null;
|
|
1617
|
-
if (flags.changed || flags.staged) {
|
|
1618
|
-
try {
|
|
1619
|
-
changedMap = getChangedLineMap(cwd, typeof flags.changed === "string" ? flags.changed : "HEAD", Boolean(flags.staged));
|
|
1620
|
-
} catch (err) {
|
|
1621
|
-
console.error(`dislop: failed to read git diff: ${err.message}`);
|
|
1622
|
-
process.exit(2);
|
|
1623
|
-
}
|
|
1624
|
-
}
|
|
1625
|
-
|
|
1626
|
-
const targets = positional.length > 0 ? positional : changedMap ? Array.from(changedMap.keys()).filter((p) => fs.existsSync(path.join(cwd, p))) : ["."];
|
|
1627
|
-
let collected;
|
|
1628
|
-
try {
|
|
1629
|
-
collected = collectFiles(targets, cwd, config, positional.length > 0);
|
|
1630
|
-
} catch (err) {
|
|
1631
|
-
console.error(`dislop: ${err.message}`);
|
|
1632
|
-
process.exit(2);
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
const allFindings = [];
|
|
1636
|
-
const allSkipped = [...collected.skipped];
|
|
1637
|
-
const allCoverageWarnings = [];
|
|
1638
|
-
const allUnused = [];
|
|
1639
|
-
const allProfiles = [];
|
|
1640
|
-
const fileMeta = [];
|
|
1641
|
-
const seenHashes = new Set();
|
|
1642
|
-
const seenPacks = new Set();
|
|
1643
|
-
const seenSources = new Set();
|
|
1644
|
-
const regPairs = [];
|
|
1645
|
-
let checkedCount = 0;
|
|
1646
|
-
let explicitUninspectable = collected.skipped.length > 0;
|
|
1647
|
-
|
|
1648
|
-
for (const item of collected.files) {
|
|
1649
|
-
if (changedMap && !changedMap.has(item.rel)) continue;
|
|
1650
|
-
let res;
|
|
1651
|
-
try {
|
|
1652
|
-
res = inspectSingleFile(item, packs, flags.pack || null, config, {
|
|
1653
|
-
includeMl,
|
|
1654
|
-
includePatterns,
|
|
1655
|
-
includeProfile,
|
|
1656
|
-
banks,
|
|
1657
|
-
register: flagRegister,
|
|
1658
|
-
});
|
|
1659
|
-
} catch (err) {
|
|
1660
|
-
console.error(`dislop: ${err.message}`);
|
|
1661
|
-
process.exit(2);
|
|
1662
|
-
}
|
|
1663
|
-
if (res.checked) {
|
|
1664
|
-
checkedCount += 1;
|
|
1665
|
-
if (res.register) regPairs.push({ register: res.register, registerSource: res.registerSource || "default" });
|
|
1666
|
-
if (res.effectivePack) seenPacks.add(res.effectivePack);
|
|
1667
|
-
if (res.packSource) seenSources.add(res.packSource);
|
|
1668
|
-
if (res.rulesetHash) seenHashes.add(res.rulesetHash);
|
|
1669
|
-
fileMeta.push({
|
|
1670
|
-
file: item.rel,
|
|
1671
|
-
modality: item.modality,
|
|
1672
|
-
effectivePack: res.effectivePack || null,
|
|
1673
|
-
packSource: res.packSource || null,
|
|
1674
|
-
});
|
|
1675
|
-
if (res.profileItem) {
|
|
1676
|
-
allProfiles.push(res.profileItem);
|
|
1677
|
-
}
|
|
1678
|
-
} else if (item.explicit) {
|
|
1679
|
-
explicitUninspectable = true;
|
|
1680
|
-
}
|
|
1681
|
-
let fileFindings = res.findings;
|
|
1682
|
-
if (changedMap && changedMap.has(item.rel)) {
|
|
1683
|
-
const allowedLines = changedMap.get(item.rel);
|
|
1684
|
-
if (allowedLines instanceof Set) {
|
|
1685
|
-
fileFindings = fileFindings.filter((f) => {
|
|
1686
|
-
const startLine = Number.isInteger(f.line) ? f.line : 1;
|
|
1687
|
-
let endLine = Number.isInteger(f.endLine) && f.endLine >= startLine ? f.endLine : startLine;
|
|
1688
|
-
if (!Number.isInteger(f.endLine) && f.span && Number.isInteger(f.span.end) && res._cpLineStarts) {
|
|
1689
|
-
const endOff = Math.max(f.span.start || 0, f.span.end - 1);
|
|
1690
|
-
endLine = Math.max(startLine, cpOffsetToLine(res._cpLineStarts, endOff));
|
|
1691
|
-
}
|
|
1692
|
-
for (let ln = startLine; ln <= endLine; ln += 1) {
|
|
1693
|
-
if (allowedLines.has(ln)) return true;
|
|
1694
|
-
}
|
|
1695
|
-
return false;
|
|
1696
|
-
});
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
if (ruleFilter) {
|
|
1700
|
-
fileFindings = fileFindings.filter((f) => ruleFilter.has(f.ruleId));
|
|
1701
|
-
}
|
|
1702
|
-
allFindings.push(...fileFindings);
|
|
1703
|
-
allSkipped.push(...res.skipped);
|
|
1704
|
-
if (res.coverageWarnings && res.coverageWarnings.length > 0) {
|
|
1705
|
-
allCoverageWarnings.push(...res.coverageWarnings);
|
|
1706
|
-
}
|
|
1707
|
-
if (reportUnused) {
|
|
1708
|
-
allUnused.push(...res.unusedSuppressions);
|
|
1709
|
-
}
|
|
1710
|
-
}
|
|
1711
|
-
|
|
1712
|
-
const shouldFail =
|
|
1713
|
-
allFindings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn]) ||
|
|
1714
|
-
(reportUnused && allUnused.length > 0);
|
|
1715
|
-
const outFindings = quiet
|
|
1716
|
-
? allFindings.filter((f) => (SEVERITY_RANK[f.severity] || 1) >= SEVERITY_RANK[failOn])
|
|
1717
|
-
: allFindings;
|
|
1718
|
-
|
|
1719
|
-
const report = {
|
|
1720
|
-
version: ENGINE_VERSION,
|
|
1721
|
-
context: summarizeReportContext(regPairs, flagRegister),
|
|
1722
|
-
rulesetHash: seenHashes.size === 1 ? Array.from(seenHashes)[0] : seenHashes.size > 1 ? fnv1aHex(Array.from(seenHashes).sort().join("|")) : null,
|
|
1723
|
-
effectivePack: seenPacks.size === 1 ? Array.from(seenPacks)[0] : seenPacks.size > 1 ? "mixed" : flags.pack || null,
|
|
1724
|
-
packSource: seenSources.size === 1 ? Array.from(seenSources)[0] : seenSources.size > 1 ? "mixed" : null,
|
|
1725
|
-
changedFilter: Boolean(flags.changed || flags.staged),
|
|
1726
|
-
files: fileMeta,
|
|
1727
|
-
checkedCount,
|
|
1728
|
-
skipped: allSkipped,
|
|
1729
|
-
coverageWarnings: allCoverageWarnings,
|
|
1730
|
-
findings: outFindings,
|
|
1731
|
-
unusedSuppressions: allUnused,
|
|
1732
|
-
...(allProfiles.length > 0 ? { profiles: allProfiles } : {}),
|
|
1733
|
-
};
|
|
1734
|
-
|
|
1735
|
-
const outReport = compactJson ? applyCompactReport(report) : report;
|
|
1736
|
-
const rendered = colorizeTextReport(formatReport(outReport, format, lang, { quiet, failOn }), useColor);
|
|
1737
|
-
if (rendered) console.log(rendered);
|
|
1738
|
-
if (useColor && !quiet && format === "text" && allFindings.length === 0 && allUnused.length === 0 && !includeMl && !includePatterns && checkedCount > 0) {
|
|
1739
|
-
console.log(lang === "zh" ? " 提示: 可加 --deep 启用统计画像与内置隐蔽套话模型。" : " hint: run with --deep to enable rhythm telemetry and Pocket ML scoring.");
|
|
1740
|
-
}
|
|
1741
|
-
|
|
1742
|
-
if (explicitUninspectable || (checkedCount === 0 && allSkipped.length > 0)) {
|
|
1743
|
-
process.exitCode = 2;
|
|
1744
|
-
return;
|
|
1745
|
-
}
|
|
1746
|
-
process.exitCode = shouldFail ? 1 : 0;
|
|
1747
|
-
}
|
|
1748
|
-
|
|
1749
|
-
const POCKET_STEALTH_VAPOR_RULE = {
|
|
1750
|
-
id: "pocket-stealth-vapor",
|
|
1751
|
-
tier: "taste",
|
|
1752
|
-
severity: "warning",
|
|
1753
|
-
category: "statistical-vapor",
|
|
1754
|
-
dimension: "discourse-rhythm",
|
|
1755
|
-
family: "rhythm/pocket-stealth-vapor",
|
|
1756
|
-
modalities: ["markdown", "text"],
|
|
1757
|
-
tags: ["pocket-ml", "stealth-vapor", "low-concreteness", "flat-cadence"],
|
|
1758
|
-
message: {
|
|
1759
|
-
en: "Paragraph scores above the bundled 15 KB Pocket ML threshold for low-concreteness, uniform-cadence AI filler despite avoiding banned buzzwords.",
|
|
1760
|
-
zh: "段落虽避开了禁用热词表,但在句长节奏、抽象名词化与低事实密度上命中内置 15 KB 轻量集成模型的温吞水套话阈值。",
|
|
1761
|
-
},
|
|
1762
|
-
deletionTest: {
|
|
1763
|
-
en: "Cut this paragraph or replace abstract cushion wrappers with one concrete event, number, file path, or direct action.",
|
|
1764
|
-
zh: "删掉整段空泛铺垫,或把抽象缓冲外壳直接换成具体事件、数字、文件路径或明确动作。",
|
|
1765
|
-
},
|
|
1766
|
-
exemplar: {
|
|
1767
|
-
bad: "During ongoing collaboration, maintaining a steady rhythm across teams helps surface operational observations early while supporting long-term alignment.",
|
|
1768
|
-
trap: "This isn't about more meetings — it's about radical operational clarity.",
|
|
1769
|
-
good: "We post a 3-line status update in #release every Tuesday at 10:00 so blockers surface before Thursday's cut.",
|
|
1770
|
-
source: "Original constructed example (Apache-2.0)",
|
|
1771
|
-
},
|
|
1772
|
-
};
|
|
1773
|
-
|
|
1774
|
-
function runExplain(args, packs, patternByRuleId) {
|
|
1775
|
-
const { flags, positional } = parseFlags(args, "explain");
|
|
1776
|
-
if (flags.help) {
|
|
1777
|
-
printSubcommandHelp("explain");
|
|
1778
|
-
return;
|
|
1779
|
-
}
|
|
1780
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
1781
|
-
assertTextOrJsonFormat(format);
|
|
1782
|
-
const ruleId = positional[0];
|
|
1783
|
-
if (!ruleId) {
|
|
1784
|
-
console.error("Usage: dislop explain <rule-id> [--lang en|zh] [--json]");
|
|
1785
|
-
process.exit(2);
|
|
1786
|
-
}
|
|
1787
|
-
const lang = flags.lang || "en";
|
|
1788
|
-
for (const pack of Object.values(packs)) {
|
|
1789
|
-
const rule = (pack.rules || []).find((r) => r.id === ruleId);
|
|
1790
|
-
if (rule) {
|
|
1791
|
-
if (format === "json") {
|
|
1792
|
-
console.log(JSON.stringify({ packId: pack.id, ...rule }, null, 2));
|
|
1793
|
-
process.exit(0);
|
|
1794
|
-
}
|
|
1795
|
-
console.log(`${rule.id} [${rule.tier} / ${rule.severity}] (pack: ${pack.id})`);
|
|
1796
|
-
console.log(`Modalities: ${(rule.modalities || []).join(", ")}`);
|
|
1797
|
-
console.log(`Why: ${rule.message?.[lang] || rule.message?.en}`);
|
|
1798
|
-
if (rule.deletionTest) {
|
|
1799
|
-
console.log(`Test: ${rule.deletionTest[lang] || rule.deletionTest.en}`);
|
|
1800
|
-
}
|
|
1801
|
-
if (rule.exemplar) {
|
|
1802
|
-
console.log(`\nBefore (bad): ${rule.exemplar.bad}`);
|
|
1803
|
-
if (rule.exemplar.trap) {
|
|
1804
|
-
console.log(`Trap (avoid): ${rule.exemplar.trap}`);
|
|
1805
|
-
}
|
|
1806
|
-
console.log(`After (good): ${rule.exemplar.good}`);
|
|
1807
|
-
if (rule.exemplar.note) {
|
|
1808
|
-
console.log(`Note: ${rule.exemplar.note[lang] || rule.exemplar.note.en}`);
|
|
1809
|
-
}
|
|
1810
|
-
}
|
|
1811
|
-
process.exit(0);
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
const pat = patternByRuleId && patternByRuleId[ruleId];
|
|
1815
|
-
if (pat) {
|
|
1816
|
-
const sev = pat.severityDefault || "info";
|
|
1817
|
-
const packId = pat.packId || "pattern-bank";
|
|
1818
|
-
const msg = pat.mechanism || pat.name || { en: "", zh: "" };
|
|
1819
|
-
const guards = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
|
|
1820
|
-
const synth = {
|
|
1821
|
-
packId,
|
|
1822
|
-
id: ruleId,
|
|
1823
|
-
tier: "taste",
|
|
1824
|
-
severity: sev,
|
|
1825
|
-
category: pat.category || "general",
|
|
1826
|
-
dimension: pat.dimension || null,
|
|
1827
|
-
modalities: pat.modalities || ["markdown", "text"],
|
|
1828
|
-
tags: pat.tags || [],
|
|
1829
|
-
message: msg,
|
|
1830
|
-
...(guards ? { deletionTest: { en: guards, zh: guards } } : {}),
|
|
1831
|
-
...(pat.exemplar ? { exemplar: pat.exemplar } : {}),
|
|
1832
|
-
};
|
|
1833
|
-
if (format === "json") {
|
|
1834
|
-
console.log(JSON.stringify(synth, null, 2));
|
|
1835
|
-
process.exit(0);
|
|
1836
|
-
}
|
|
1837
|
-
console.log(`${synth.id} [${synth.tier} / ${synth.severity}] (pack: ${packId})`);
|
|
1838
|
-
console.log(`Modalities: ${synth.modalities.join(", ")}`);
|
|
1839
|
-
console.log(`Why: ${msg[lang] || msg.en}`);
|
|
1840
|
-
if (guards) console.log(`Guards: ${guards}`);
|
|
1841
|
-
if (pat.exemplar) {
|
|
1842
|
-
console.log(`\nBefore (bad): ${pat.exemplar.bad}`);
|
|
1843
|
-
if (pat.exemplar.trap) console.log(`Trap (avoid): ${pat.exemplar.trap}`);
|
|
1844
|
-
console.log(`After (good): ${pat.exemplar.good}`);
|
|
1845
|
-
}
|
|
1846
|
-
process.exit(0);
|
|
1847
|
-
}
|
|
1848
|
-
if (ruleId === "pocket-stealth-vapor") {
|
|
1849
|
-
const r = POCKET_STEALTH_VAPOR_RULE;
|
|
1850
|
-
if (format === "json") {
|
|
1851
|
-
console.log(JSON.stringify({ packId: "pocket-model", ...r }, null, 2));
|
|
1852
|
-
process.exit(0);
|
|
1853
|
-
}
|
|
1854
|
-
console.log(`${r.id} [${r.tier} / ${r.severity}] (pack: pocket-model)`);
|
|
1855
|
-
console.log(`Modalities: ${r.modalities.join(", ")}`);
|
|
1856
|
-
console.log(`Why: ${r.message[lang] || r.message.en}`);
|
|
1857
|
-
console.log(`Test: ${r.deletionTest[lang] || r.deletionTest.en}`);
|
|
1858
|
-
console.log(`\nBefore (bad): ${r.exemplar.bad}`);
|
|
1859
|
-
console.log(`Trap (avoid): ${r.exemplar.trap}`);
|
|
1860
|
-
console.log(`After (good): ${r.exemplar.good}`);
|
|
1861
|
-
process.exit(0);
|
|
1862
|
-
}
|
|
1863
|
-
console.error(`dislop: unknown rule '${ruleId}'`);
|
|
1864
|
-
process.exit(2);
|
|
1865
|
-
}
|
|
1866
|
-
|
|
1867
|
-
function runPacks(args, packs) {
|
|
1868
|
-
const { flags } = parseFlags(args, "packs");
|
|
1869
|
-
if (flags.help) {
|
|
1870
|
-
printSubcommandHelp("packs");
|
|
1871
|
-
return;
|
|
1872
|
-
}
|
|
1873
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
1874
|
-
assertTextOrJsonFormat(format);
|
|
1875
|
-
const list = Object.values(packs).map((p) => ({
|
|
1876
|
-
id: p.id,
|
|
1877
|
-
version: p.version,
|
|
1878
|
-
tier: p.tier,
|
|
1879
|
-
extends: p.extends || [],
|
|
1880
|
-
name: p.name,
|
|
1881
|
-
modalities: p.modalities,
|
|
1882
|
-
ruleCount: (p.rules || []).length,
|
|
1883
|
-
summary: p.summary,
|
|
1884
|
-
}));
|
|
1885
|
-
if (format === "json") {
|
|
1886
|
-
console.log(JSON.stringify(list, null, 2));
|
|
1887
|
-
return;
|
|
1888
|
-
}
|
|
1889
|
-
for (const p of list) {
|
|
1890
|
-
console.log(`${p.id.padEnd(18)} [${p.tier}] (${p.ruleCount} rules) — ${p.name.en} / ${p.name.zh}`);
|
|
1891
|
-
console.log(` modalities: ${p.modalities.join(", ")}`);
|
|
1892
|
-
}
|
|
1893
|
-
}
|
|
1894
|
-
|
|
1895
|
-
const VALID_MODALITIES = new Set(["markdown", "text", "html", "css", "jsx", "svg", "docx", "pptx", "pdf", "image"]);
|
|
1896
|
-
const VALID_SEVERITIES = new Set(["error", "warning", "info"]);
|
|
1897
|
-
const VALID_TIERS = new Set(["invariant", "taste"]);
|
|
1898
|
-
|
|
1899
|
-
function runCatalog(args, packs, patternByRuleId) {
|
|
1900
|
-
const { flags, positional } = parseFlags(args, "catalog");
|
|
1901
|
-
if (flags.help) {
|
|
1902
|
-
printSubcommandHelp("catalog");
|
|
1903
|
-
return;
|
|
1904
|
-
}
|
|
1905
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
1906
|
-
const lang = flags.lang || "en";
|
|
1907
|
-
if (!["text", "json", "md"].includes(format)) {
|
|
1908
|
-
console.error(`dislop: invalid --format '${format}' (expected text, json, or md)`);
|
|
1909
|
-
process.exit(2);
|
|
1910
|
-
}
|
|
1911
|
-
if (flags.severity && !VALID_SEVERITIES.has(flags.severity)) {
|
|
1912
|
-
console.error(`dislop: invalid --severity '${flags.severity}' (expected error, warning, or info)`);
|
|
1913
|
-
process.exit(2);
|
|
1914
|
-
}
|
|
1915
|
-
if (flags.modality && !VALID_MODALITIES.has(flags.modality)) {
|
|
1916
|
-
console.error(`dislop: invalid --modality '${flags.modality}'`);
|
|
1917
|
-
process.exit(2);
|
|
1918
|
-
}
|
|
1919
|
-
if (flags.tier && !VALID_TIERS.has(flags.tier)) {
|
|
1920
|
-
console.error(`dislop: invalid --tier '${flags.tier}' (expected invariant or taste)`);
|
|
1921
|
-
process.exit(2);
|
|
1922
|
-
}
|
|
1923
|
-
|
|
1924
|
-
const query = flags.query || positional.join(" ").trim() || "";
|
|
1925
|
-
const limit = flags.limit ? Number(flags.limit) : null;
|
|
1926
|
-
const entries = buildCatalog(packs, patternByRuleId);
|
|
1927
|
-
const result = queryCatalog(entries, {
|
|
1928
|
-
query,
|
|
1929
|
-
pack: flags.pack || null,
|
|
1930
|
-
category: flags.category || null,
|
|
1931
|
-
dimension: flags.dimension || null,
|
|
1932
|
-
family: flags.family || null,
|
|
1933
|
-
modality: flags.modality || null,
|
|
1934
|
-
severity: flags.severity || null,
|
|
1935
|
-
tier: flags.tier || null,
|
|
1936
|
-
includeExemplars: flags["no-exemplars"] ? false : true,
|
|
1937
|
-
limit: Number.isInteger(limit) && limit > 0 ? limit : null,
|
|
1938
|
-
});
|
|
1939
|
-
|
|
1940
|
-
if (format === "json") {
|
|
1941
|
-
console.log(JSON.stringify(result, null, 2));
|
|
1942
|
-
return;
|
|
1943
|
-
}
|
|
1944
|
-
if (format === "md") {
|
|
1945
|
-
const rows = [
|
|
1946
|
-
"| Rule | Pack | Severity | Category | Modalities | Description |",
|
|
1947
|
-
"|---|---|---|---|---|---|",
|
|
1948
|
-
...result.items.map((item) => {
|
|
1949
|
-
const msg = (item.message?.[lang] || item.message?.en || "").replace(/\|/g, "\\|");
|
|
1950
|
-
return `| \`${item.id}\` | \`${item.packId}\` | \`${item.severity}\` | \`${item.category}\` | ${(item.modalities || []).join(", ")} | ${msg} |`;
|
|
1951
|
-
}),
|
|
1952
|
-
];
|
|
1953
|
-
console.log(rows.join("\n"));
|
|
1954
|
-
return;
|
|
1955
|
-
}
|
|
1956
|
-
|
|
1957
|
-
console.log(`dislop catalog: ${result.matched} / ${result.total} rule(s) matched`);
|
|
1958
|
-
for (const item of result.items) {
|
|
1959
|
-
const msg = item.message?.[lang] || item.message?.en || "";
|
|
1960
|
-
console.log(` [${item.severity.padEnd(7)}] ${item.id.padEnd(30)} (${item.packId} · ${item.category}) — ${msg}`);
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1963
|
-
|
|
1964
|
-
function runPackTest(args, packs) {
|
|
1965
|
-
const { flags } = parseFlags(args, "pack-test");
|
|
1966
|
-
if (flags.help) {
|
|
1967
|
-
printSubcommandHelp("pack-test");
|
|
1968
|
-
return;
|
|
1969
|
-
}
|
|
1970
|
-
const errors = [];
|
|
1971
|
-
let assertions = 0;
|
|
1972
|
-
|
|
1973
|
-
for (const pack of Object.values(packs)) {
|
|
1974
|
-
if (pack.schema !== "dislop.pack/2") {
|
|
1975
|
-
errors.push(`${pack.id}: expected schema 'dislop.pack/2'`);
|
|
1976
|
-
}
|
|
1977
|
-
const effective = resolveEffectivePack(pack.id, packs, {});
|
|
1978
|
-
for (const rule of pack.rules || []) {
|
|
1979
|
-
if (!rule.deletionTest?.en || !rule.deletionTest?.zh) {
|
|
1980
|
-
errors.push(`${pack.id}/${rule.id}: missing bilingual deletionTest`);
|
|
1981
|
-
}
|
|
1982
|
-
if (!rule.exemplar?.bad || !rule.exemplar?.good || !rule.exemplar?.source) {
|
|
1983
|
-
errors.push(`${pack.id}/${rule.id}: missing exemplar (bad/good/source)`);
|
|
1984
|
-
}
|
|
1985
|
-
const hits = rule.fixtures?.hit || [];
|
|
1986
|
-
const cleans = rule.fixtures?.clean || [];
|
|
1987
|
-
if (hits.length === 0 || cleans.length === 0) {
|
|
1988
|
-
errors.push(`${pack.id}/${rule.id}: requires at least 1 hit and 1 clean fixture`);
|
|
1989
|
-
}
|
|
1990
|
-
const sampleMod = (rule.modalities && rule.modalities[0]) || "markdown";
|
|
1991
|
-
for (const h of hits) {
|
|
1992
|
-
assertions += 1;
|
|
1993
|
-
const res = auditText(h, { filename: `fixture.${sampleMod}`, modality: sampleMod, pack: effective, allowSyntheticFixtures: true });
|
|
1994
|
-
if (!res.findings.some((f) => f.ruleId === rule.id)) {
|
|
1995
|
-
errors.push(`${pack.id}/${rule.id}: hit fixture did NOT trigger rule: ${JSON.stringify(h)}`);
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
for (const c of cleans) {
|
|
1999
|
-
assertions += 1;
|
|
2000
|
-
const res = auditText(c, { filename: `fixture.${sampleMod}`, modality: sampleMod, pack: effective, allowSyntheticFixtures: true });
|
|
2001
|
-
if (res.findings.some((f) => f.ruleId === rule.id)) {
|
|
2002
|
-
errors.push(`${pack.id}/${rule.id}: clean fixture FALSELY triggered rule: ${JSON.stringify(c)}`);
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
// Lint regex patterns against unbounded `.*`
|
|
2006
|
-
for (const pat of rule.patterns || []) {
|
|
2007
|
-
if (/\.\*/.test(pat)) {
|
|
2008
|
-
errors.push(`${pack.id}/${rule.id}: unbounded '.*' forbidden in portable pack regex: ${pat}`);
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
// Validate registerOverrides + fixtures.register
|
|
2012
|
-
if (rule.registerOverrides) {
|
|
2013
|
-
if (rule.tier === "invariant") {
|
|
2014
|
-
errors.push(`${pack.id}/${rule.id}: invariant rules cannot define registerOverrides`);
|
|
2015
|
-
}
|
|
2016
|
-
const ovEntries = Object.entries(rule.registerOverrides);
|
|
2017
|
-
for (const [rk, rov] of ovEntries) {
|
|
2018
|
-
if (!VALID_REGISTERS.includes(rk) || rk === "unspecified") {
|
|
2019
|
-
errors.push(`${pack.id}/${rule.id}: invalid registerOverrides key '${rk}'`);
|
|
2020
|
-
}
|
|
2021
|
-
if (rov?.severity && SEVERITY_RANK[rov.severity] > SEVERITY_RANK[rule.severity]) {
|
|
2022
|
-
errors.push(`${pack.id}/${rule.id}: registerOverrides['${rk}'] cannot raise severity above '${rule.severity}'`);
|
|
2023
|
-
}
|
|
2024
|
-
}
|
|
2025
|
-
const regFixtures = rule.fixtures?.register || [];
|
|
2026
|
-
if (regFixtures.length === 0) {
|
|
2027
|
-
errors.push(`${pack.id}/${rule.id}: registerOverrides requires at least 1 fixtures.register assertion`);
|
|
2028
|
-
}
|
|
2029
|
-
for (const rf of regFixtures) {
|
|
2030
|
-
assertions += 1;
|
|
2031
|
-
const res = auditText(rf.text, {
|
|
2032
|
-
filename: `fixture.${sampleMod}`,
|
|
2033
|
-
modality: sampleMod,
|
|
2034
|
-
pack: effective,
|
|
2035
|
-
allowSyntheticFixtures: true,
|
|
2036
|
-
register: rf.register,
|
|
2037
|
-
});
|
|
2038
|
-
const hit = res.findings.find((f) => f.ruleId === rule.id);
|
|
2039
|
-
if (rf.expect === "skip") {
|
|
2040
|
-
if (hit) errors.push(`${pack.id}/${rule.id}: expected register '${rf.register}' to skip`);
|
|
2041
|
-
} else if (!hit || hit.severity !== rf.expect) {
|
|
2042
|
-
errors.push(`${pack.id}/${rule.id}: register '${rf.register}' expected '${rf.expect}', got '${hit?.severity || "none"}'`);
|
|
2043
|
-
}
|
|
2044
|
-
}
|
|
2045
|
-
}
|
|
2046
|
-
}
|
|
2047
|
-
}
|
|
2048
|
-
|
|
2049
|
-
if (errors.length > 0) {
|
|
2050
|
-
console.error(`dislop pack-test: FAILED (${errors.length} error(s) across ${assertions} assertions)`);
|
|
2051
|
-
for (const e of errors) console.error(` - ${e}`);
|
|
2052
|
-
process.exit(1);
|
|
2053
|
-
}
|
|
2054
|
-
console.log(`dislop pack-test: ok (${Object.keys(packs).length} packs, ${assertions} fixture assertions passed)`);
|
|
2055
|
-
}
|
|
2056
|
-
|
|
2057
|
-
function runInit(args = []) {
|
|
2058
|
-
const { flags } = parseFlags(args, "init");
|
|
2059
|
-
if (flags.help) {
|
|
2060
|
-
printSubcommandHelp("init");
|
|
2061
|
-
return;
|
|
2062
|
-
}
|
|
2063
|
-
const cwd = process.cwd();
|
|
2064
|
-
const cfgPath = path.join(cwd, ".dislop.json");
|
|
2065
|
-
if (!fs.existsSync(cfgPath)) {
|
|
2066
|
-
const starter = {
|
|
2067
|
-
failOn: "error",
|
|
2068
|
-
ignore: ["vendor/**", "dist/**"],
|
|
2069
|
-
overrides: [{ files: ["docs/**/*.md"], pack: "business-brief" }],
|
|
2070
|
-
allow: [],
|
|
2071
|
-
rules: {},
|
|
2072
|
-
};
|
|
2073
|
-
fs.writeFileSync(cfgPath, JSON.stringify(starter, null, 2) + "\n", "utf8");
|
|
2074
|
-
console.log(`Created ${cfgPath}`);
|
|
2075
|
-
} else {
|
|
2076
|
-
console.log(`${cfgPath} already exists`);
|
|
2077
|
-
}
|
|
2078
|
-
|
|
2079
|
-
const giPath = path.join(cwd, ".gitignore");
|
|
2080
|
-
const localEntry = ".dislop.local.json";
|
|
2081
|
-
if (fs.existsSync(giPath)) {
|
|
2082
|
-
const cur = fs.readFileSync(giPath, "utf8");
|
|
2083
|
-
if (!cur.split(/\r?\n/).includes(localEntry)) {
|
|
2084
|
-
fs.writeFileSync(giPath, cur.replace(/\s*$/, "\n") + localEntry + "\n", "utf8");
|
|
2085
|
-
console.log(`Added ${localEntry} to .gitignore`);
|
|
2086
|
-
}
|
|
2087
|
-
} else if (fs.existsSync(path.join(cwd, ".git"))) {
|
|
2088
|
-
fs.writeFileSync(giPath, localEntry + "\n", "utf8");
|
|
2089
|
-
console.log(`Created .gitignore with ${localEntry}`);
|
|
2090
|
-
}
|
|
2091
|
-
}
|
|
2092
|
-
|
|
2093
|
-
// ---------- MCP Stdio Server ----------
|
|
2094
|
-
|
|
2095
|
-
function runMcpServer(packs, patternByRuleId) {
|
|
2096
|
-
const cwd = process.cwd();
|
|
2097
|
-
const catalogEntries = buildCatalog(packs, patternByRuleId);
|
|
2098
|
-
const rl = readline.createInterface({ input: process.stdin, terminal: false });
|
|
2099
|
-
|
|
2100
|
-
function send(msg) {
|
|
2101
|
-
process.stdout.write(JSON.stringify(msg) + "\n");
|
|
2102
|
-
}
|
|
2103
|
-
|
|
2104
|
-
function toolResult(id, payload, isError = false) {
|
|
2105
|
-
send({
|
|
2106
|
-
jsonrpc: "2.0",
|
|
2107
|
-
id,
|
|
2108
|
-
result: {
|
|
2109
|
-
isError,
|
|
2110
|
-
content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
|
|
2111
|
-
},
|
|
2112
|
-
});
|
|
2113
|
-
}
|
|
2114
|
-
|
|
2115
|
-
function formatRuleForExplain(rule, packId, lang) {
|
|
2116
|
-
const cleanLang = lang === "en" || lang === "zh" ? lang : null;
|
|
2117
|
-
const localizeObj = (obj) => {
|
|
2118
|
-
if (!obj || typeof obj !== "object") return obj;
|
|
2119
|
-
if (!cleanLang) return obj;
|
|
2120
|
-
return { [cleanLang]: obj[cleanLang] || obj.en || "" };
|
|
2121
|
-
};
|
|
2122
|
-
const out = {
|
|
2123
|
-
packId,
|
|
2124
|
-
id: rule.id,
|
|
2125
|
-
tier: rule.tier,
|
|
2126
|
-
severity: rule.severity,
|
|
2127
|
-
...(rule.category ? { category: rule.category } : {}),
|
|
2128
|
-
...(rule.family ? { family: rule.family } : {}),
|
|
2129
|
-
modalities: rule.modalities || [],
|
|
2130
|
-
...(Array.isArray(rule.tags) ? { tags: rule.tags } : {}),
|
|
2131
|
-
message: localizeObj(rule.message),
|
|
2132
|
-
deletionTest: localizeObj(rule.deletionTest),
|
|
2133
|
-
};
|
|
2134
|
-
if (rule.exemplar) {
|
|
2135
|
-
out.exemplar = {
|
|
2136
|
-
...rule.exemplar,
|
|
2137
|
-
...(rule.exemplar.note ? { note: localizeObj(rule.exemplar.note) } : {}),
|
|
2138
|
-
};
|
|
2139
|
-
}
|
|
2140
|
-
return out;
|
|
2141
|
-
}
|
|
2142
|
-
|
|
2143
|
-
function formatFindingsForMcp(findings, verbosity, lang) {
|
|
2144
|
-
const cleanLang = lang === "en" || lang === "zh" ? lang : null;
|
|
2145
|
-
const localizeObj = (obj) => {
|
|
2146
|
-
if (!obj || typeof obj !== "object" || !cleanLang) return obj;
|
|
2147
|
-
return { [cleanLang]: obj[cleanLang] || obj.en || "" };
|
|
2148
|
-
};
|
|
2149
|
-
const localizeRevision = (rev) => {
|
|
2150
|
-
if (!rev || typeof rev !== "object") return null;
|
|
2151
|
-
if (!cleanLang) return rev;
|
|
2152
|
-
return {
|
|
2153
|
-
...rev,
|
|
2154
|
-
instruction: localizeObj(rev.instruction),
|
|
2155
|
-
avoid: localizeObj(rev.avoid),
|
|
2156
|
-
};
|
|
2157
|
-
};
|
|
2158
|
-
if (verbosity === "full") {
|
|
2159
|
-
if (!cleanLang) return findings;
|
|
2160
|
-
return findings.map((f) => ({
|
|
2161
|
-
...f,
|
|
2162
|
-
message: localizeObj(f.message),
|
|
2163
|
-
deletionTest: localizeObj(f.deletionTest),
|
|
2164
|
-
revision: localizeRevision(f.revision),
|
|
2165
|
-
}));
|
|
2166
|
-
}
|
|
2167
|
-
return findings.map((f) => ({
|
|
2168
|
-
fingerprint: f.fingerprint,
|
|
2169
|
-
ruleId: f.ruleId,
|
|
2170
|
-
tier: f.tier ?? "taste",
|
|
2171
|
-
severity: f.severity,
|
|
2172
|
-
confidence: f.confidence || "medium",
|
|
2173
|
-
fixStrategy: f.fixStrategy || deriveFixStrategy({ id: f.ruleId, family: f.family }),
|
|
2174
|
-
family: f.family ?? (f.dimension ? `${f.dimension}/${f.ruleId}` : null),
|
|
2175
|
-
file: f.file,
|
|
2176
|
-
modality: f.modality,
|
|
2177
|
-
location: f.location,
|
|
2178
|
-
line: f.line,
|
|
2179
|
-
col: f.col,
|
|
2180
|
-
match: f.match,
|
|
2181
|
-
message: localizeObj(f.message),
|
|
2182
|
-
deletionTest: f.deletionTest ? localizeObj(f.deletionTest) : null,
|
|
2183
|
-
revision: localizeRevision(f.revision),
|
|
2184
|
-
}));
|
|
2185
|
-
}
|
|
2186
|
-
|
|
2187
|
-
const OFFLINE_TOOL_ANNOTATIONS = {
|
|
2188
|
-
readOnlyHint: true,
|
|
2189
|
-
idempotentHint: true,
|
|
2190
|
-
destructiveHint: false,
|
|
2191
|
-
openWorldHint: false,
|
|
2192
|
-
};
|
|
2193
|
-
const tools = [
|
|
2194
|
-
{
|
|
2195
|
-
name: "dislop_check",
|
|
2196
|
-
description:
|
|
2197
|
-
"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`.",
|
|
2198
|
-
annotations: OFFLINE_TOOL_ANNOTATIONS,
|
|
2199
|
-
inputSchema: {
|
|
2200
|
-
type: "object",
|
|
2201
|
-
properties: {
|
|
2202
|
-
text: { type: "string", description: "Draft text to inspect in memory" },
|
|
2203
|
-
path: { type: "string", description: "Workspace-relative file path (.md, .html, .css, .jsx, .svg, .png, .jpg, .jpeg, .webp, .docx, .pptx, .pdf)" },
|
|
2204
|
-
pack: { type: "string", description: "Style pack ID (auto, business-brief, engineering-spec, regulated-comms, literary-essay, deck-and-ui, executive-deck)" },
|
|
2205
|
-
register: { type: "string", enum: ["auto", ...VALID_REGISTERS], description: "Optional writing register override (auto, unspecified, official, casual, argumentative, technical, marketing, narrative)" },
|
|
2206
|
-
filename: { type: "string", description: "Virtual filename hint when inspecting `text`" },
|
|
2207
|
-
profile: { type: "boolean", description: "Include 5-axis rhythm & concreteness telemetry on text/markdown (default true)" },
|
|
2208
|
-
deep: { type: "boolean", description: "Enable thorough inspection (Pocket ML + extended 6-dimension pattern bank)" },
|
|
2209
|
-
ml: { type: "boolean", description: "Enable bundled 15 KB Pocket ML stealth-vapor paragraph detection (default false)" },
|
|
2210
|
-
patterns: { type: "boolean", description: "Include extended 6-dimension pattern-bank probes (default false)" },
|
|
2211
|
-
verbosity: { type: "string", enum: ["compact", "full"], description: "Default compact (omits per-hit exemplars to save context tokens; pass full to inline exemplars)" },
|
|
2212
|
-
lang: { type: "string", enum: ["en", "zh"], description: "Optional single-locale filter for finding messages" },
|
|
2213
|
-
},
|
|
2214
|
-
},
|
|
2215
|
-
},
|
|
2216
|
-
{
|
|
2217
|
-
name: "dislop_verify",
|
|
2218
|
-
description:
|
|
2219
|
-
"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).",
|
|
2220
|
-
annotations: OFFLINE_TOOL_ANNOTATIONS,
|
|
2221
|
-
inputSchema: {
|
|
2222
|
-
type: "object",
|
|
2223
|
-
properties: {
|
|
2224
|
-
before: { type: "string", description: "Original text before revision (required unless `path` is provided)" },
|
|
2225
|
-
after: { type: "string", description: "Revised text after revision (required unless `path` is provided)" },
|
|
2226
|
-
path: { type: "string", description: "Workspace-relative file path to compare working tree against `gitRef`" },
|
|
2227
|
-
gitRef: { type: "string", description: "Git ref baseline when `path` is given (default HEAD)" },
|
|
2228
|
-
filename: { type: "string", description: "Optional virtual filename hint when passing `before`/`after`" },
|
|
2229
|
-
pack: { type: "string", description: "Optional pack ID or 'auto' to also verify findingsDelta" },
|
|
2230
|
-
register: { type: "string", enum: ["auto", ...VALID_REGISTERS], description: "Optional writing register override (auto, unspecified, official, casual, argumentative, technical, marketing, narrative)" },
|
|
2231
|
-
keep: { type: "array", items: { type: "string" }, description: "Protected terms/concepts that must stay intact in the revision" },
|
|
2232
|
-
allowAdded: { type: "boolean", description: "Allow new numbers not present in original (default false)" },
|
|
2233
|
-
strict: { type: "boolean", description: "Fail `ok` on any anti-degradation warning in addition to hard fact/error checks" },
|
|
2234
|
-
},
|
|
2235
|
-
},
|
|
2236
|
-
},
|
|
2237
|
-
{
|
|
2238
|
-
name: "dislop_rules",
|
|
2239
|
-
description: "Unified rule lookup: pass `ruleId` to explain a rule, filters (`query`/`pack`/`dimension`) to search, or empty object to list all packs.",
|
|
2240
|
-
annotations: OFFLINE_TOOL_ANNOTATIONS,
|
|
2241
|
-
inputSchema: {
|
|
2242
|
-
type: "object",
|
|
2243
|
-
properties: {
|
|
2244
|
-
ruleId: { type: "string", description: "Optional rule ID to explain with before/trap/after examples" },
|
|
2245
|
-
query: { type: "string", description: "Optional keyword search query" },
|
|
2246
|
-
pack: { type: "string", description: "Filter rules by style pack ID" },
|
|
2247
|
-
category: { type: "string", description: "Filter rules by category identifier" },
|
|
2248
|
-
dimension: { type: "string", description: "Filter pattern bank rules by writing dimension" },
|
|
2249
|
-
family: { type: "string", description: "Filter pattern bank rules by pattern family" },
|
|
2250
|
-
modality: { type: "string", description: "Filter rules by target content modality (text, web, doc, visual)" },
|
|
2251
|
-
severity: { type: "string", enum: ["error", "warning", "info"], description: "Filter rules by severity level" },
|
|
2252
|
-
tier: { type: "string", enum: ["invariant", "taste"], description: "Filter rules by enforcement tier (invariant or taste)" },
|
|
2253
|
-
lang: { type: "string", enum: ["en", "zh"], description: "Optional single-locale filter for rule descriptions and examples" },
|
|
2254
|
-
includeExemplars: { type: "boolean", description: "Include before/trap/after examples in search results (default false)" },
|
|
2255
|
-
limit: { type: "integer", minimum: 1, maximum: 100, description: "Maximum number of matching rules to return (1..100)" },
|
|
2256
|
-
},
|
|
2257
|
-
},
|
|
2258
|
-
},
|
|
2259
|
-
{
|
|
2260
|
-
name: "dislop_voice_extract",
|
|
2261
|
-
description:
|
|
2262
|
-
"Extract a deterministic offline `dislop.voice/1` personal style card from 1-15 clean author samples (0 network calls, 0 uploads).",
|
|
2263
|
-
annotations: OFFLINE_TOOL_ANNOTATIONS,
|
|
2264
|
-
inputSchema: {
|
|
2265
|
-
type: "object",
|
|
2266
|
-
properties: {
|
|
2267
|
-
samples: {
|
|
2268
|
-
type: "array",
|
|
2269
|
-
items: { type: "string" },
|
|
2270
|
-
minItems: 1,
|
|
2271
|
-
maxItems: 15,
|
|
2272
|
-
description: "1 to 15 clean sample passages written by the author",
|
|
2273
|
-
},
|
|
2274
|
-
lang: { type: "string", enum: ["auto", "en", "zh"], description: "Language hint for style extraction (auto, en, or zh)" },
|
|
2275
|
-
},
|
|
2276
|
-
required: ["samples"],
|
|
2277
|
-
},
|
|
2278
|
-
},
|
|
2279
|
-
{
|
|
2280
|
-
name: "dislop_model_score",
|
|
2281
|
-
description:
|
|
2282
|
-
"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).",
|
|
2283
|
-
annotations: OFFLINE_TOOL_ANNOTATIONS,
|
|
2284
|
-
inputSchema: {
|
|
2285
|
-
type: "object",
|
|
2286
|
-
properties: {
|
|
2287
|
-
text: { type: "string", description: "Draft text to score with bundled Pocket ML" },
|
|
2288
|
-
threshold: { type: "number", description: "Optional paragraph flag threshold (0..1)" },
|
|
2289
|
-
},
|
|
2290
|
-
required: ["text"],
|
|
2291
|
-
},
|
|
2292
|
-
},
|
|
2293
|
-
{
|
|
2294
|
-
name: "dislop_model_status",
|
|
2295
|
-
description:
|
|
2296
|
-
"Inspect bundled models, installed optional model weights, hardware memory budget, and recommended optional local model tier.",
|
|
2297
|
-
annotations: OFFLINE_TOOL_ANNOTATIONS,
|
|
2298
|
-
inputSchema: {
|
|
2299
|
-
type: "object",
|
|
2300
|
-
properties: {},
|
|
2301
|
-
},
|
|
2302
|
-
},
|
|
2303
|
-
];
|
|
2304
|
-
|
|
2305
|
-
rl.on("line", (line) => {
|
|
2306
|
-
const trimmed = line.trim();
|
|
2307
|
-
if (!trimmed) return;
|
|
2308
|
-
let req;
|
|
2309
|
-
try {
|
|
2310
|
-
req = JSON.parse(trimmed);
|
|
2311
|
-
} catch {
|
|
2312
|
-
return;
|
|
2313
|
-
}
|
|
2314
|
-
if (!req || typeof req !== "object" || Array.isArray(req)) {
|
|
2315
|
-
send({
|
|
2316
|
-
jsonrpc: "2.0",
|
|
2317
|
-
id: null,
|
|
2318
|
-
error: { code: -32600, message: "Invalid Request: expected JSON-RPC object" },
|
|
2319
|
-
});
|
|
2320
|
-
return;
|
|
2321
|
-
}
|
|
2322
|
-
const { id, method } = req;
|
|
2323
|
-
if (id === undefined || id === null) return;
|
|
2324
|
-
const rawParams = req.params;
|
|
2325
|
-
if (rawParams !== undefined && (!rawParams || typeof rawParams !== "object" || Array.isArray(rawParams))) {
|
|
2326
|
-
send({
|
|
2327
|
-
jsonrpc: "2.0",
|
|
2328
|
-
id,
|
|
2329
|
-
error: { code: -32600, message: "Invalid Request: params must be an object" },
|
|
2330
|
-
});
|
|
2331
|
-
return;
|
|
2332
|
-
}
|
|
2333
|
-
const params = rawParams || {};
|
|
2334
|
-
|
|
2335
|
-
if (method === "initialize") {
|
|
2336
|
-
const clientVersion = params.protocolVersion || "2024-11-05";
|
|
2337
|
-
send({
|
|
2338
|
-
jsonrpc: "2.0",
|
|
2339
|
-
id,
|
|
2340
|
-
result: {
|
|
2341
|
-
protocolVersion: clientVersion,
|
|
2342
|
-
capabilities: { tools: {} },
|
|
2343
|
-
serverInfo: { name: "dislop", version: ENGINE_VERSION },
|
|
2344
|
-
},
|
|
2345
|
-
});
|
|
2346
|
-
return;
|
|
2347
|
-
}
|
|
2348
|
-
|
|
2349
|
-
if (method === "ping") {
|
|
2350
|
-
send({ jsonrpc: "2.0", id, result: {} });
|
|
2351
|
-
return;
|
|
2352
|
-
}
|
|
2353
|
-
|
|
2354
|
-
if (method === "tools/list") {
|
|
2355
|
-
send({ jsonrpc: "2.0", id, result: { tools } });
|
|
2356
|
-
return;
|
|
2357
|
-
}
|
|
2358
|
-
|
|
2359
|
-
if (method === "tools/call") {
|
|
2360
|
-
const name = params.name;
|
|
2361
|
-
const rawArgs = params.arguments;
|
|
2362
|
-
if (rawArgs !== undefined && (!rawArgs || typeof rawArgs !== "object" || Array.isArray(rawArgs))) {
|
|
2363
|
-
send({
|
|
2364
|
-
jsonrpc: "2.0",
|
|
2365
|
-
id,
|
|
2366
|
-
error: { code: -32602, message: "Invalid params: arguments must be an object" },
|
|
2367
|
-
});
|
|
2368
|
-
return;
|
|
2369
|
-
}
|
|
2370
|
-
const args = rawArgs || {};
|
|
2371
|
-
try {
|
|
2372
|
-
const resolveWorkspaceFileMcp = (relOrAbsPath) => {
|
|
2373
|
-
const realCwd = fs.realpathSync(cwd);
|
|
2374
|
-
const resolved = path.resolve(cwd, relOrAbsPath);
|
|
2375
|
-
if (!fs.existsSync(resolved)) {
|
|
2376
|
-
const lexReal = path.relative(realCwd, path.resolve(realCwd, relOrAbsPath));
|
|
2377
|
-
const lexCwd = path.relative(path.resolve(cwd), resolved);
|
|
2378
|
-
const escapesBoth =
|
|
2379
|
-
(lexReal === ".." || lexReal.startsWith(`..${path.sep}`) || path.isAbsolute(lexReal)) &&
|
|
2380
|
-
(lexCwd === ".." || lexCwd.startsWith(`..${path.sep}`) || path.isAbsolute(lexCwd));
|
|
2381
|
-
return {
|
|
2382
|
-
error: escapesBoth
|
|
2383
|
-
? "Path must stay within the current workspace directory."
|
|
2384
|
-
: `File not found: ${relOrAbsPath}`,
|
|
2385
|
-
};
|
|
2386
|
-
}
|
|
2387
|
-
if (!fs.statSync(resolved).isFile()) {
|
|
2388
|
-
return { error: `File not found: ${relOrAbsPath}` };
|
|
2389
|
-
}
|
|
2390
|
-
const realTarget = fs.realpathSync(resolved);
|
|
2391
|
-
const rel = path.relative(realCwd, realTarget);
|
|
2392
|
-
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
2393
|
-
return { error: "Path must stay within the current workspace directory." };
|
|
2394
|
-
}
|
|
2395
|
-
return { realTarget, posixRel: rel.split(path.sep).join("/") };
|
|
2396
|
-
};
|
|
2397
|
-
|
|
2398
|
-
const resolveExplainById = (ruleId, langArg) => {
|
|
2399
|
-
for (const p of Object.values(packs)) {
|
|
2400
|
-
const rule = (p.rules || []).find((r) => r.id === ruleId);
|
|
2401
|
-
if (rule) return formatRuleForExplain(rule, p.id, langArg);
|
|
2402
|
-
}
|
|
2403
|
-
const pat = patternByRuleId && patternByRuleId[ruleId];
|
|
2404
|
-
if (pat) {
|
|
2405
|
-
const guards = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
|
|
2406
|
-
const synthRule = {
|
|
2407
|
-
id: ruleId,
|
|
2408
|
-
tier: "taste",
|
|
2409
|
-
severity: pat.severityDefault || "info",
|
|
2410
|
-
category: pat.category || "general",
|
|
2411
|
-
family: pat.dimension ? `${pat.dimension}/${ruleId}` : "pattern-bank",
|
|
2412
|
-
modalities: pat.modalities || ["markdown", "text"],
|
|
2413
|
-
tags: pat.tags || [],
|
|
2414
|
-
message: pat.mechanism || pat.name || { en: "", zh: "" },
|
|
2415
|
-
...(guards ? { deletionTest: { en: guards, zh: guards } } : {}),
|
|
2416
|
-
...(pat.exemplar ? { exemplar: pat.exemplar } : {}),
|
|
2417
|
-
};
|
|
2418
|
-
return formatRuleForExplain(synthRule, pat.packId || "pattern-bank", langArg);
|
|
2419
|
-
}
|
|
2420
|
-
if (ruleId === "pocket-stealth-vapor") {
|
|
2421
|
-
return formatRuleForExplain(POCKET_STEALTH_VAPOR_RULE, "pocket-model", langArg);
|
|
2422
|
-
}
|
|
2423
|
-
return null;
|
|
2424
|
-
};
|
|
2425
|
-
|
|
2426
|
-
if (name === "dislop_rules") {
|
|
2427
|
-
if (args.ruleId) {
|
|
2428
|
-
const explained = resolveExplainById(args.ruleId, args.lang);
|
|
2429
|
-
if (explained) toolResult(id, explained);
|
|
2430
|
-
else toolResult(id, { error: `Unknown ruleId '${args.ruleId}'` }, true);
|
|
2431
|
-
return;
|
|
2432
|
-
}
|
|
2433
|
-
const hasFilter = Boolean(
|
|
2434
|
-
args.query || args.pack || args.category || args.dimension || args.family || args.modality || args.severity || args.tier
|
|
2435
|
-
);
|
|
2436
|
-
if (hasFilter) {
|
|
2437
|
-
const result = queryCatalog(catalogEntries, {
|
|
2438
|
-
query: args.query || "",
|
|
2439
|
-
pack: args.pack || null,
|
|
2440
|
-
category: args.category || null,
|
|
2441
|
-
dimension: args.dimension || null,
|
|
2442
|
-
family: args.family || null,
|
|
2443
|
-
modality: args.modality || null,
|
|
2444
|
-
severity: args.severity || null,
|
|
2445
|
-
tier: args.tier || null,
|
|
2446
|
-
includeExemplars: args.includeExemplars !== false,
|
|
2447
|
-
limit: Number.isInteger(args.limit) && args.limit > 0 ? args.limit : null,
|
|
2448
|
-
});
|
|
2449
|
-
toolResult(id, result);
|
|
2450
|
-
return;
|
|
2451
|
-
}
|
|
2452
|
-
const list = Object.values(packs).map((p) => ({
|
|
2453
|
-
id: p.id,
|
|
2454
|
-
tier: p.tier,
|
|
2455
|
-
name: p.name,
|
|
2456
|
-
modalities: p.modalities,
|
|
2457
|
-
ruleCount: (p.rules || []).length,
|
|
2458
|
-
summary: p.summary,
|
|
2459
|
-
}));
|
|
2460
|
-
toolResult(id, { packs: list });
|
|
2461
|
-
return;
|
|
2462
|
-
}
|
|
2463
|
-
|
|
2464
|
-
if (name === "dislop_verify") {
|
|
2465
|
-
const liveConfig = loadConfig(cwd);
|
|
2466
|
-
const hasBefore = typeof args.before === "string";
|
|
2467
|
-
const hasAfter = typeof args.after === "string";
|
|
2468
|
-
const hasPath = typeof args.path === "string" && args.path.trim().length > 0;
|
|
2469
|
-
let beforeText;
|
|
2470
|
-
let afterText;
|
|
2471
|
-
let fn = args.filename || "draft.md";
|
|
2472
|
-
if (hasPath) {
|
|
2473
|
-
const ws = resolveWorkspaceFileMcp(args.path);
|
|
2474
|
-
if (ws.error) {
|
|
2475
|
-
toolResult(id, { error: ws.error }, true);
|
|
2476
|
-
return;
|
|
2477
|
-
}
|
|
2478
|
-
fn = ws.posixRel;
|
|
2479
|
-
afterText = decodeUtf8Strict(fs.readFileSync(ws.realTarget));
|
|
2480
|
-
beforeText = readGitBaselineForFile(ws.realTarget, typeof args.gitRef === "string" && args.gitRef.trim() ? args.gitRef.trim() : "HEAD");
|
|
2481
|
-
} else if (hasBefore && hasAfter) {
|
|
2482
|
-
beforeText = args.before;
|
|
2483
|
-
afterText = args.after;
|
|
2484
|
-
} else {
|
|
2485
|
-
toolResult(id, { error: "Provide both `before` and `after` strings, or a workspace `path`." }, true);
|
|
2486
|
-
return;
|
|
2487
|
-
}
|
|
2488
|
-
const mod = detectModality(fn) || "markdown";
|
|
2489
|
-
const fileCfg = resolveConfigForFile(fn, liveConfig);
|
|
2490
|
-
let argRegister = null;
|
|
2491
|
-
if (args.register !== undefined) {
|
|
2492
|
-
if (typeof args.register !== "string") {
|
|
2493
|
-
toolResult(id, { error: `Invalid register (expected string: auto, ${VALID_REGISTERS.join(", ")})` }, true);
|
|
2494
|
-
return;
|
|
2495
|
-
}
|
|
2496
|
-
const normReg = args.register.trim().toLowerCase();
|
|
2497
|
-
if (!normReg || (normReg !== "auto" && !VALID_REGISTERS.includes(normReg))) {
|
|
2498
|
-
toolResult(id, { error: `Invalid register '${args.register}' (expected auto, ${VALID_REGISTERS.join(", ")})` }, true);
|
|
2499
|
-
return;
|
|
2500
|
-
}
|
|
2501
|
-
argRegister = normReg;
|
|
2502
|
-
}
|
|
2503
|
-
const packRes = resolveTextPackAndSource(afterText, fn, mod, args.pack || "auto", fileCfg, packs);
|
|
2504
|
-
const keepTerms = Array.isArray(args.keep)
|
|
2505
|
-
? args.keep
|
|
2506
|
-
: typeof args.keep === "string"
|
|
2507
|
-
? args.keep.split(",").map((x) => x.trim()).filter(Boolean)
|
|
2508
|
-
: [];
|
|
2509
|
-
const out = verifyRevisionBundle(beforeText, afterText, {
|
|
2510
|
-
filename: fn,
|
|
2511
|
-
modality: mod,
|
|
2512
|
-
pack: packRes.pack,
|
|
2513
|
-
config: fileCfg,
|
|
2514
|
-
register: argRegister,
|
|
2515
|
-
keepTerms,
|
|
2516
|
-
allowAdded: Boolean(args.allowAdded),
|
|
2517
|
-
strict: Boolean(args.strict),
|
|
2518
|
-
});
|
|
2519
|
-
out.effectivePack = packRes.effectivePack;
|
|
2520
|
-
out.packSource = packRes.packSource;
|
|
2521
|
-
toolResult(id, out);
|
|
2522
|
-
return;
|
|
2523
|
-
}
|
|
2524
|
-
|
|
2525
|
-
if (name === "dislop_packs") {
|
|
2526
|
-
const list = Object.values(packs).map((p) => ({
|
|
2527
|
-
id: p.id,
|
|
2528
|
-
tier: p.tier,
|
|
2529
|
-
name: p.name,
|
|
2530
|
-
modalities: p.modalities,
|
|
2531
|
-
ruleCount: (p.rules || []).length,
|
|
2532
|
-
summary: p.summary,
|
|
2533
|
-
}));
|
|
2534
|
-
toolResult(id, { packs: list });
|
|
2535
|
-
return;
|
|
2536
|
-
}
|
|
2537
|
-
|
|
2538
|
-
if (name === "dislop_catalog") {
|
|
2539
|
-
const result = queryCatalog(catalogEntries, {
|
|
2540
|
-
query: args.query || "",
|
|
2541
|
-
pack: args.pack || null,
|
|
2542
|
-
category: args.category || null,
|
|
2543
|
-
dimension: args.dimension || null,
|
|
2544
|
-
family: args.family || null,
|
|
2545
|
-
modality: args.modality || null,
|
|
2546
|
-
severity: args.severity || null,
|
|
2547
|
-
tier: args.tier || null,
|
|
2548
|
-
includeExemplars: args.includeExemplars !== false,
|
|
2549
|
-
limit: Number.isInteger(args.limit) && args.limit > 0 ? args.limit : null,
|
|
2550
|
-
});
|
|
2551
|
-
toolResult(id, result);
|
|
2552
|
-
return;
|
|
2553
|
-
}
|
|
2554
|
-
|
|
2555
|
-
if (name === "dislop_explain") {
|
|
2556
|
-
if (!args.ruleId) {
|
|
2557
|
-
toolResult(id, { error: "Missing required argument `ruleId`" }, true);
|
|
2558
|
-
return;
|
|
2559
|
-
}
|
|
2560
|
-
for (const p of Object.values(packs)) {
|
|
2561
|
-
const rule = (p.rules || []).find((r) => r.id === args.ruleId);
|
|
2562
|
-
if (rule) {
|
|
2563
|
-
toolResult(id, formatRuleForExplain(rule, p.id, args.lang));
|
|
2564
|
-
return;
|
|
2565
|
-
}
|
|
2566
|
-
}
|
|
2567
|
-
const pat = patternByRuleId && patternByRuleId[args.ruleId];
|
|
2568
|
-
if (pat) {
|
|
2569
|
-
const guards = Array.isArray(pat.falsePositiveGuards) ? pat.falsePositiveGuards.join(" ") : "";
|
|
2570
|
-
const synthRule = {
|
|
2571
|
-
id: args.ruleId,
|
|
2572
|
-
tier: "taste",
|
|
2573
|
-
severity: pat.severityDefault || "info",
|
|
2574
|
-
category: pat.category || "general",
|
|
2575
|
-
family: pat.dimension ? `${pat.dimension}/${args.ruleId}` : "pattern-bank",
|
|
2576
|
-
modalities: pat.modalities || ["markdown", "text"],
|
|
2577
|
-
tags: pat.tags || [],
|
|
2578
|
-
message: pat.mechanism || pat.name || { en: "", zh: "" },
|
|
2579
|
-
...(guards ? { deletionTest: { en: guards, zh: guards } } : {}),
|
|
2580
|
-
...(pat.exemplar ? { exemplar: pat.exemplar } : {}),
|
|
2581
|
-
};
|
|
2582
|
-
toolResult(id, formatRuleForExplain(synthRule, pat.packId || "pattern-bank", args.lang));
|
|
2583
|
-
return;
|
|
2584
|
-
}
|
|
2585
|
-
if (args.ruleId === "pocket-stealth-vapor") {
|
|
2586
|
-
toolResult(id, formatRuleForExplain(POCKET_STEALTH_VAPOR_RULE, "pocket-model", args.lang));
|
|
2587
|
-
return;
|
|
2588
|
-
}
|
|
2589
|
-
toolResult(id, { error: `Unknown ruleId '${args.ruleId}'` }, true);
|
|
2590
|
-
return;
|
|
2591
|
-
}
|
|
2592
|
-
|
|
2593
|
-
if (name === "dislop_check") {
|
|
2594
|
-
const hasText = typeof args.text === "string";
|
|
2595
|
-
const hasPath = typeof args.path === "string" && args.path.trim().length > 0;
|
|
2596
|
-
if (hasText === hasPath) {
|
|
2597
|
-
toolResult(
|
|
2598
|
-
id,
|
|
2599
|
-
{ error: "Provide exactly one of `text` (in-memory string) or `path` (workspace file path)." },
|
|
2600
|
-
true
|
|
2601
|
-
);
|
|
2602
|
-
return;
|
|
2603
|
-
}
|
|
2604
|
-
|
|
2605
|
-
const liveConfig = loadConfig(cwd);
|
|
2606
|
-
const verbosity = args.verbosity === "full" ? "full" : "compact";
|
|
2607
|
-
const includeMl = Boolean(args.ml || args.deep);
|
|
2608
|
-
const includePatterns = Boolean(args.patterns || args.deep);
|
|
2609
|
-
const wantProfile = args.profile !== false;
|
|
2610
|
-
const banks = includePatterns ? loadPatternBanks() : null;
|
|
2611
|
-
let argRegister = null;
|
|
2612
|
-
if (args.register !== undefined && args.register !== null) {
|
|
2613
|
-
if (typeof args.register !== "string") {
|
|
2614
|
-
toolResult(
|
|
2615
|
-
id,
|
|
2616
|
-
{ error: `Invalid register (expected string: auto, ${VALID_REGISTERS.join(", ")})` },
|
|
2617
|
-
true
|
|
2618
|
-
);
|
|
2619
|
-
return;
|
|
2620
|
-
}
|
|
2621
|
-
const rawReg = args.register;
|
|
2622
|
-
const normReg = rawReg.trim().toLowerCase();
|
|
2623
|
-
if (!normReg || (normReg !== "auto" && !VALID_REGISTERS.includes(normReg))) {
|
|
2624
|
-
toolResult(
|
|
2625
|
-
id,
|
|
2626
|
-
{ error: `Invalid register '${rawReg}' (expected auto, ${VALID_REGISTERS.join(", ")})` },
|
|
2627
|
-
true
|
|
2628
|
-
);
|
|
2629
|
-
return;
|
|
2630
|
-
}
|
|
2631
|
-
argRegister = normReg;
|
|
2632
|
-
}
|
|
2633
|
-
|
|
2634
|
-
if (hasText) {
|
|
2635
|
-
const fn = args.filename || "draft.md";
|
|
2636
|
-
const mod = detectModality(fn) || "markdown";
|
|
2637
|
-
const fileCfg = resolveConfigForFile(fn, liveConfig);
|
|
2638
|
-
const { pack, effectivePack, packSource } = resolveTextPackAndSource(args.text, fn, mod, args.pack || null, fileCfg, packs);
|
|
2639
|
-
const regInfo = resolveRegister(args.text, { filename: fn, flagRegister: argRegister, config: fileCfg });
|
|
2640
|
-
const res = auditText(args.text, { filename: fn, modality: mod, pack, config: fileCfg, register: argRegister });
|
|
2641
|
-
let findings = res.findings;
|
|
2642
|
-
if (includePatterns) {
|
|
2643
|
-
findings = mergePatternBankFindings(
|
|
2644
|
-
findings,
|
|
2645
|
-
auditPatterns(args.text, { filename: fn, modality: mod, banks, config: fileCfg }).findings,
|
|
2646
|
-
{ packs, pack, register: regInfo.register, config: fileCfg }
|
|
2647
|
-
);
|
|
2648
|
-
}
|
|
2649
|
-
const needsCoverageProfile = codePointLength(args.text) >= 2000 || mod === "html";
|
|
2650
|
-
const profile = PROSE_ML_MODALITIES.has(mod) && (wantProfile || includeMl || needsCoverageProfile)
|
|
2651
|
-
? analyzeTextProfile(args.text, { modality: mod, config: fileCfg })
|
|
2652
|
-
: null;
|
|
2653
|
-
if (includeMl && PROSE_ML_MODALITIES.has(mod)) {
|
|
2654
|
-
const mlSrc = mod === "html" || mod === "svg" ? buildZones(args.text, mod, fileCfg).prose : args.text;
|
|
2655
|
-
findings = [
|
|
2656
|
-
...findings,
|
|
2657
|
-
...buildPocketMlFindings(mlSrc, fn, findings, null, {
|
|
2658
|
-
profile,
|
|
2659
|
-
modality: mod,
|
|
2660
|
-
register: regInfo.register,
|
|
2661
|
-
}).findings,
|
|
2662
|
-
];
|
|
2663
|
-
}
|
|
2664
|
-
const formatted = formatFindingsForMcp(findings, verbosity, args.lang);
|
|
2665
|
-
toolResult(id, {
|
|
2666
|
-
pack: effectivePack,
|
|
2667
|
-
packSource,
|
|
2668
|
-
rulesetHash: computeRulesetHash(pack),
|
|
2669
|
-
modality: mod,
|
|
2670
|
-
context: { register: regInfo.register, registerSource: regInfo.registerSource },
|
|
2671
|
-
checked: true,
|
|
2672
|
-
skipped: [],
|
|
2673
|
-
coverageWarnings: collectTextCoverageWarnings(args.text, mod, fn, profile),
|
|
2674
|
-
count: formatted.length,
|
|
2675
|
-
findings: formatted,
|
|
2676
|
-
...(verbosity === "compact" && formatted.length > 0
|
|
2677
|
-
? { explainHint: "Call dislop_explain(ruleId) for before/trap/after examples." }
|
|
2678
|
-
: {}),
|
|
2679
|
-
...(wantProfile && profile ? { profile } : {}),
|
|
2680
|
-
});
|
|
2681
|
-
return;
|
|
2682
|
-
}
|
|
2683
|
-
|
|
2684
|
-
const realCwd = fs.realpathSync(cwd);
|
|
2685
|
-
const resolved = path.resolve(cwd, args.path);
|
|
2686
|
-
if (!fs.existsSync(resolved)) {
|
|
2687
|
-
const lexReal = path.relative(realCwd, path.resolve(realCwd, args.path));
|
|
2688
|
-
const lexCwd = path.relative(path.resolve(cwd), resolved);
|
|
2689
|
-
const escapesBoth =
|
|
2690
|
-
(lexReal === ".." || lexReal.startsWith(`..${path.sep}`) || path.isAbsolute(lexReal)) &&
|
|
2691
|
-
(lexCwd === ".." || lexCwd.startsWith(`..${path.sep}`) || path.isAbsolute(lexCwd));
|
|
2692
|
-
toolResult(
|
|
2693
|
-
id,
|
|
2694
|
-
{
|
|
2695
|
-
error: escapesBoth
|
|
2696
|
-
? "Path must stay within the current workspace directory."
|
|
2697
|
-
: `File not found: ${args.path}`,
|
|
2698
|
-
},
|
|
2699
|
-
true
|
|
2700
|
-
);
|
|
2701
|
-
return;
|
|
2702
|
-
}
|
|
2703
|
-
if (!fs.statSync(resolved).isFile()) {
|
|
2704
|
-
toolResult(id, { error: `File not found: ${args.path}` }, true);
|
|
2705
|
-
return;
|
|
2706
|
-
}
|
|
2707
|
-
const realTarget = fs.realpathSync(resolved);
|
|
2708
|
-
const rel = path.relative(realCwd, realTarget);
|
|
2709
|
-
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
2710
|
-
toolResult(id, { error: "Path must stay within the current workspace directory." }, true);
|
|
2711
|
-
return;
|
|
2712
|
-
}
|
|
2713
|
-
const mod = detectModality(realTarget);
|
|
2714
|
-
if (!mod) {
|
|
2715
|
-
toolResult(id, { error: `Unsupported file extension for '${args.path}'` }, true);
|
|
2716
|
-
return;
|
|
2717
|
-
}
|
|
2718
|
-
const posixRel = rel.split(path.sep).join("/");
|
|
2719
|
-
const res = inspectSingleFile(
|
|
2720
|
-
{ absPath: realTarget, rel: posixRel, modality: mod },
|
|
2721
|
-
packs,
|
|
2722
|
-
args.pack || null,
|
|
2723
|
-
liveConfig,
|
|
2724
|
-
{ includeMl, includePatterns, includeProfile: wantProfile, banks, register: argRegister }
|
|
2725
|
-
);
|
|
2726
|
-
const profile = res.profileItem ? res.profileItem.profile : null;
|
|
2727
|
-
const formatted = formatFindingsForMcp(res.findings, verbosity, args.lang);
|
|
2728
|
-
toolResult(id, {
|
|
2729
|
-
pack: res.effectivePack || pickPackForFile(posixRel, mod, args.pack || null, liveConfig),
|
|
2730
|
-
packSource: res.packSource || null,
|
|
2731
|
-
rulesetHash: res.rulesetHash || null,
|
|
2732
|
-
modality: mod,
|
|
2733
|
-
context: { register: res.register || "unspecified", registerSource: res.registerSource || "default" },
|
|
2734
|
-
checked: res.checked,
|
|
2735
|
-
skipped: res.skipped,
|
|
2736
|
-
coverageWarnings: res.coverageWarnings || [],
|
|
2737
|
-
count: formatted.length,
|
|
2738
|
-
findings: formatted,
|
|
2739
|
-
...(verbosity === "compact" && formatted.length > 0
|
|
2740
|
-
? { explainHint: "Call dislop_explain(ruleId) for before/trap/after examples." }
|
|
2741
|
-
: {}),
|
|
2742
|
-
...(profile ? { profile } : {}),
|
|
2743
|
-
});
|
|
2744
|
-
return;
|
|
2745
|
-
}
|
|
2746
|
-
|
|
2747
|
-
if (name === "dislop_voice_extract_offline" || name === "dislop_voice_extract") {
|
|
2748
|
-
if (!Array.isArray(args.samples) || args.samples.length === 0) {
|
|
2749
|
-
toolResult(id, { error: "Non-empty `samples` string array is required." }, true);
|
|
2750
|
-
return;
|
|
2751
|
-
}
|
|
2752
|
-
if (args.samples.length > 15) {
|
|
2753
|
-
toolResult(id, { error: "Provide at most 15 sample passages per call." }, true);
|
|
2754
|
-
return;
|
|
2755
|
-
}
|
|
2756
|
-
if (args.samples.some((s) => typeof s !== "string")) {
|
|
2757
|
-
toolResult(id, { error: "Every element in `samples` must be a string." }, true);
|
|
2758
|
-
return;
|
|
2759
|
-
}
|
|
2760
|
-
const nonBlankSamples = args.samples.map((s) => s.trim()).filter(Boolean);
|
|
2761
|
-
if (nonBlankSamples.length === 0) {
|
|
2762
|
-
toolResult(id, { error: "At least one non-empty sample passage is required." }, true);
|
|
2763
|
-
return;
|
|
2764
|
-
}
|
|
2765
|
-
const voice = extractVoiceProfileOffline(nonBlankSamples, { lang: args.lang || "auto" });
|
|
2766
|
-
toolResult(id, voice);
|
|
2767
|
-
return;
|
|
2768
|
-
}
|
|
2769
|
-
|
|
2770
|
-
if (name === "dislop_model_score") {
|
|
2771
|
-
if (typeof args.text !== "string") {
|
|
2772
|
-
toolResult(id, { error: "Required string argument `text` missing." }, true);
|
|
2773
|
-
return;
|
|
2774
|
-
}
|
|
2775
|
-
if (args.threshold !== undefined && args.threshold !== null) {
|
|
2776
|
-
if (typeof args.threshold !== "number" || !Number.isFinite(args.threshold) || args.threshold < 0 || args.threshold > 1) {
|
|
2777
|
-
toolResult(id, { error: "`threshold` must be a number between 0 and 1." }, true);
|
|
2778
|
-
return;
|
|
2779
|
-
}
|
|
2780
|
-
}
|
|
2781
|
-
const thr = typeof args.threshold === "number" ? args.threshold : null;
|
|
2782
|
-
toolResult(id, analyzeDocumentWithPocketModels(args.text, { threshold: thr }));
|
|
2783
|
-
return;
|
|
2784
|
-
}
|
|
2785
|
-
|
|
2786
|
-
if (name === "dislop_model_status") {
|
|
2787
|
-
let rulesCount = 0;
|
|
2788
|
-
for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
|
|
2789
|
-
buildModelStatusReport({
|
|
2790
|
-
packsCount: Object.keys(packs).length,
|
|
2791
|
-
rulesCount,
|
|
2792
|
-
probeLoopback: false,
|
|
2793
|
-
})
|
|
2794
|
-
.then((st) => toolResult(id, st))
|
|
2795
|
-
.catch((e) => toolResult(id, { error: e.message }, true));
|
|
2796
|
-
return;
|
|
2797
|
-
}
|
|
2798
|
-
|
|
2799
|
-
toolResult(id, { error: `Unknown tool '${name}'` }, true);
|
|
2800
|
-
} catch (err) {
|
|
2801
|
-
toolResult(id, { error: err.message }, true);
|
|
2802
|
-
}
|
|
2803
|
-
return;
|
|
2804
|
-
}
|
|
2805
|
-
|
|
2806
|
-
send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });
|
|
2807
|
-
});
|
|
2808
|
-
}
|
|
2809
|
-
|
|
2810
|
-
function runResources(rest, packs) {
|
|
2811
|
-
const { flags } = parseFlags(rest, "resources");
|
|
2812
|
-
if (flags.help) {
|
|
2813
|
-
printSubcommandHelp("resources");
|
|
2814
|
-
return;
|
|
2815
|
-
}
|
|
2816
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
2817
|
-
assertTextOrJsonFormat(format);
|
|
2818
|
-
const asJson = format === "json";
|
|
2819
|
-
const payload = {
|
|
2820
|
-
schema: "dislop.resources/1",
|
|
2821
|
-
offlineCheck: true,
|
|
2822
|
-
note: "'dislop check' runs 100% locally with zero network requests and zero file uploads.",
|
|
2823
|
-
bundledPacks: Object.keys(packs).sort(),
|
|
2824
|
-
staticResources: {
|
|
2825
|
-
llmsIndex: "https://dislop.com/llms.txt",
|
|
2826
|
-
catalog: "https://dislop.com/catalog.json",
|
|
2827
|
-
awesomeIndex: "https://dislop.com/awesome/index.json",
|
|
2828
|
-
mcpServerCard: "https://dislop.com/.well-known/mcp/server-card.json",
|
|
2829
|
-
agentSkillsIndex: "https://dislop.com/.well-known/agent-skills/index.json",
|
|
2830
|
-
tasks: [
|
|
2831
|
-
"https://dislop.com/tasks/business-doc.md",
|
|
2832
|
-
"https://dislop.com/tasks/web-and-deck.md",
|
|
2833
|
-
"https://dislop.com/tasks/editorial-writing.md",
|
|
2834
|
-
"https://dislop.com/tasks/pre-release-gate.md",
|
|
2835
|
-
],
|
|
2836
|
-
ruleTemplate: "https://dislop.com/rules/<rule-id>.md",
|
|
2837
|
-
},
|
|
2838
|
-
optionalCloudMcp: {
|
|
2839
|
-
url: "https://dislop.com/mcp",
|
|
2840
|
-
oauthMetadata: "https://dislop.com/.well-known/oauth-protected-resource/mcp",
|
|
2841
|
-
pricingAndFreeToken: "https://dislop.com/#pricing",
|
|
2842
|
-
freeToolsNoLogin: ["dislop_check", "dislop_verify", "dislop_rules"],
|
|
2843
|
-
tools: [
|
|
2844
|
-
"dislop_check",
|
|
2845
|
-
"dislop_verify",
|
|
2846
|
-
"dislop_rules",
|
|
2847
|
-
"dislop_review",
|
|
2848
|
-
"dislop_deslop",
|
|
2849
|
-
"dislop_office",
|
|
2850
|
-
"dislop_visual_review",
|
|
2851
|
-
"dislop_voice_extract",
|
|
2852
|
-
"dislop_voice_manage",
|
|
2853
|
-
"dislop_account",
|
|
2854
|
-
],
|
|
2855
|
-
},
|
|
2856
|
-
};
|
|
2857
|
-
if (asJson) {
|
|
2858
|
-
console.log(JSON.stringify(payload, null, 2));
|
|
2859
|
-
return;
|
|
2860
|
-
}
|
|
2861
|
-
console.log(`dislop v${ENGINE_VERSION} resources (dislop check makes 0 network requests)`);
|
|
2862
|
-
console.log(`\nBundled offline packs: ${payload.bundledPacks.join(", ")}`);
|
|
2863
|
-
console.log(`\nFree read-only static resources (dislop.com):`);
|
|
2864
|
-
console.log(` - Agent index : ${payload.staticResources.llmsIndex}`);
|
|
2865
|
-
console.log(` - Full catalog: ${payload.staticResources.catalog}`);
|
|
2866
|
-
console.log(` - Awesome 90 : ${payload.staticResources.awesomeIndex}`);
|
|
2867
|
-
console.log(` - MCP card : ${payload.staticResources.mcpServerCard}`);
|
|
2868
|
-
console.log(` - Skills index: ${payload.staticResources.agentSkillsIndex}`);
|
|
2869
|
-
console.log(` - Rule card : ${payload.staticResources.ruleTemplate}`);
|
|
2870
|
-
console.log(`\nOptional hosted Cloud Remote MCP (0-credit check/verify/rules need no login; 30 free credits/mo after sign-in):`);
|
|
2871
|
-
console.log(` - Endpoint : ${payload.optionalCloudMcp.url}`);
|
|
2872
|
-
console.log(` - Free token : ${payload.optionalCloudMcp.pricingAndFreeToken}`);
|
|
2873
|
-
}
|
|
2874
|
-
|
|
2875
|
-
function loadPatternBanks(customPatternsDir = PATTERNS_DIR) {
|
|
2876
|
-
const bankDir = path.join(customPatternsDir, "banks");
|
|
2877
|
-
const out = {};
|
|
2878
|
-
if (!fs.existsSync(bankDir)) return out;
|
|
2879
|
-
for (const entry of fs.readdirSync(bankDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
2880
|
-
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
2881
|
-
const data = JSON.parse(fs.readFileSync(path.join(bankDir, entry.name), "utf8"));
|
|
2882
|
-
out[data.id || entry.name.replace(/\.json$/, "")] = data;
|
|
2883
|
-
}
|
|
2884
|
-
return out;
|
|
2885
|
-
}
|
|
2886
|
-
|
|
2887
|
-
function runPatterns(args) {
|
|
2888
|
-
const { flags, positional } = parseFlags(args, "patterns");
|
|
2889
|
-
if (flags.help) {
|
|
2890
|
-
printSubcommandHelp("patterns");
|
|
2891
|
-
return;
|
|
2892
|
-
}
|
|
2893
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
2894
|
-
assertTextOrJsonFormat(format);
|
|
2895
|
-
const lang = flags.lang || "en";
|
|
2896
|
-
const banks = loadPatternBanks();
|
|
2897
|
-
const angles = flags.angle ? String(flags.angle).split(",").map((s) => s.trim()).filter(Boolean) : null;
|
|
2898
|
-
|
|
2899
|
-
let text = "";
|
|
2900
|
-
let filename = flags["stdin-filename"] || "stdin.md";
|
|
2901
|
-
let modality = detectModality(filename) || "markdown";
|
|
2902
|
-
let ooxml = null;
|
|
2903
|
-
|
|
2904
|
-
if (positional.length === 0 || positional[0] === "-") {
|
|
2905
|
-
text = fs.readFileSync(0, "utf8");
|
|
2906
|
-
} else {
|
|
2907
|
-
const abs = path.resolve(process.cwd(), positional[0]);
|
|
2908
|
-
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
2909
|
-
console.error(`dislop: file not found: ${positional[0]}`);
|
|
2910
|
-
process.exit(2);
|
|
2911
|
-
}
|
|
2912
|
-
filename = positional[0];
|
|
2913
|
-
const detected = detectModality(abs);
|
|
2914
|
-
if (!detected) {
|
|
2915
|
-
console.error(`dislop: unsupported file extension for '${positional[0]}'`);
|
|
2916
|
-
process.exit(2);
|
|
2917
|
-
}
|
|
2918
|
-
modality = detected;
|
|
2919
|
-
if (modality === "pdf" || modality === "image") {
|
|
2920
|
-
console.error(`dislop: unsupported modality '${modality}' for patterns (use 'dislop check' for PDF and image files)`);
|
|
2921
|
-
process.exit(2);
|
|
2922
|
-
}
|
|
2923
|
-
const buf = fs.readFileSync(abs);
|
|
2924
|
-
try {
|
|
2925
|
-
if (modality === "pptx" || modality === "docx") {
|
|
2926
|
-
ooxml = readZipXmlEntries(buf);
|
|
2927
|
-
} else {
|
|
2928
|
-
text = decodeUtf8Strict(buf);
|
|
2929
|
-
}
|
|
2930
|
-
} catch (err) {
|
|
2931
|
-
console.error(`dislop: uninspectable ${modality.toUpperCase()} file '${positional[0]}': ${err.message}`);
|
|
2932
|
-
process.exit(2);
|
|
2933
|
-
}
|
|
2934
|
-
}
|
|
2935
|
-
|
|
2936
|
-
const profile = analyzePatternProfile(text, { filename, modality, banks, angles, ooxml });
|
|
2937
|
-
if (format === "json") {
|
|
2938
|
-
console.log(JSON.stringify(profile, null, 2));
|
|
2939
|
-
return;
|
|
2940
|
-
}
|
|
2941
|
-
if (profile.findingCount === 0) {
|
|
2942
|
-
console.log(`dislop patterns: ok (${filename}, 0 pattern findings)`);
|
|
2943
|
-
return;
|
|
2944
|
-
}
|
|
2945
|
-
console.log(`dislop patterns: ${profile.findingCount} finding(s) in ${filename} (dimensions: ${profile.activeDimensions.join(", ")})`);
|
|
2946
|
-
for (const f of profile.findings) {
|
|
2947
|
-
const msg = f.message?.[lang] || f.message?.en || "";
|
|
2948
|
-
console.log(` [${f.severity.toUpperCase()}] ${f.file}:${f.location} ${f.ruleId} (${f.detectionAngle}${f.metric ? ` · ${f.metric}` : ""})`);
|
|
2949
|
-
console.log(` match: "${f.match}"`);
|
|
2950
|
-
console.log(` why: ${msg}`);
|
|
2951
|
-
}
|
|
2952
|
-
}
|
|
2953
|
-
|
|
2954
|
-
function runVoice(args) {
|
|
2955
|
-
const { flags, positional } = parseFlags(args, "voice");
|
|
2956
|
-
if (flags.help) {
|
|
2957
|
-
printSubcommandHelp("voice");
|
|
2958
|
-
return;
|
|
2959
|
-
}
|
|
2960
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
2961
|
-
assertTextOrJsonFormat(format);
|
|
2962
|
-
const lang = flags.lang || "auto";
|
|
2963
|
-
const samples = [];
|
|
2964
|
-
|
|
2965
|
-
if (positional.length === 0 || positional[0] === "-") {
|
|
2966
|
-
const raw = fs.readFileSync(0, "utf8");
|
|
2967
|
-
samples.push(...raw.split(/\n\s*\n/).map((s) => s.trim()).filter(Boolean));
|
|
2968
|
-
} else {
|
|
2969
|
-
for (const p of positional) {
|
|
2970
|
-
const abs = path.resolve(process.cwd(), p);
|
|
2971
|
-
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
2972
|
-
console.error(`dislop: file not found: ${p}`);
|
|
2973
|
-
process.exit(2);
|
|
2974
|
-
}
|
|
2975
|
-
samples.push(decodeUtf8Strict(fs.readFileSync(abs)));
|
|
2976
|
-
}
|
|
2977
|
-
}
|
|
2978
|
-
if (samples.length === 0) {
|
|
2979
|
-
console.error("dislop voice: provide at least one non-empty sample file or stdin text");
|
|
2980
|
-
process.exit(2);
|
|
2981
|
-
}
|
|
2982
|
-
|
|
2983
|
-
const result = extractVoiceProfileOffline(samples, { lang });
|
|
2984
|
-
if (flags.output) {
|
|
2985
|
-
const outAbs = path.resolve(process.cwd(), String(flags.output));
|
|
2986
|
-
fs.mkdirSync(path.dirname(outAbs), { recursive: true });
|
|
2987
|
-
fs.writeFileSync(outAbs, JSON.stringify(result, null, 2) + "\n", "utf8");
|
|
2988
|
-
}
|
|
2989
|
-
if (flags.json || flags.format === "json") {
|
|
2990
|
-
console.log(JSON.stringify(result, null, 2));
|
|
2991
|
-
return;
|
|
2992
|
-
}
|
|
2993
|
-
const s = result.stylometrics;
|
|
2994
|
-
console.log(`dislop voice (${result.mode}, 0 network calls)`);
|
|
2995
|
-
console.log(` samples=${s.sampleCount} · sentences=${s.sentenceCount} · mean=${s.meanLength} · cv=${s.lengthCV} · band=[${s.targetLengthBand.join(", ")}]`);
|
|
2996
|
-
console.log(` tone: ${result.profile.tone}`);
|
|
2997
|
-
for (const h of result.profile.sentenceHabits) {
|
|
2998
|
-
console.log(` - ${h}`);
|
|
2999
|
-
}
|
|
3000
|
-
}
|
|
3001
|
-
|
|
3002
|
-
async function promptInteractiveTier(defaultTier, lang) {
|
|
3003
|
-
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
3004
|
-
const q =
|
|
3005
|
-
lang === "zh"
|
|
3006
|
-
? `\n请选择要选装的本地模型档位 [none / fast / balanced / quality](回车默认 ${defaultTier}):`
|
|
3007
|
-
: `\nChoose optional local model tier [none / fast / balanced / quality] (Enter for '${defaultTier}'): `;
|
|
3008
|
-
return new Promise((resolve) => {
|
|
3009
|
-
rl.question(q, (ans) => {
|
|
3010
|
-
rl.close();
|
|
3011
|
-
const val = String(ans || "").trim().toLowerCase();
|
|
3012
|
-
resolve(val || defaultTier);
|
|
3013
|
-
});
|
|
3014
|
-
});
|
|
3015
|
-
}
|
|
3016
|
-
|
|
3017
|
-
async function runLocalDeslopCli(target, flags, packs) {
|
|
3018
|
-
const lang = flags.lang || "en";
|
|
3019
|
-
let rawText = "";
|
|
3020
|
-
let filename = flags["stdin-filename"] || "draft.md";
|
|
3021
|
-
if (!target || target === "-") {
|
|
3022
|
-
rawText = fs.readFileSync(0, "utf8");
|
|
3023
|
-
} else {
|
|
3024
|
-
const abs = path.resolve(process.cwd(), target);
|
|
3025
|
-
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
3026
|
-
console.error(`dislop: file not found: ${target}`);
|
|
3027
|
-
process.exit(2);
|
|
3028
|
-
}
|
|
3029
|
-
filename = path.basename(abs);
|
|
3030
|
-
rawText = decodeUtf8Strict(fs.readFileSync(abs));
|
|
3031
|
-
}
|
|
3032
|
-
const modality = detectModality(filename) || "markdown";
|
|
3033
|
-
const config = loadConfig(process.cwd(), flags.config || null);
|
|
3034
|
-
let flagRegister = null;
|
|
3035
|
-
if (flags.register !== undefined) {
|
|
3036
|
-
const norm = String(flags.register).trim().toLowerCase();
|
|
3037
|
-
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
3038
|
-
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
3039
|
-
process.exit(2);
|
|
3040
|
-
}
|
|
3041
|
-
flagRegister = norm;
|
|
3042
|
-
}
|
|
3043
|
-
const fileCfg = resolveConfigForFile(filename, config);
|
|
3044
|
-
const regInfo = resolveRegister(rawText, { filename, flagRegister, config: fileCfg });
|
|
3045
|
-
const explicitPack =
|
|
3046
|
-
flags.pack === "auto"
|
|
3047
|
-
? predictPackWithPocketRouter(rawText).recommendedPack
|
|
3048
|
-
: flags.pack || null;
|
|
3049
|
-
const packId = pickPackForFile(filename, modality, explicitPack, config);
|
|
3050
|
-
const pack = resolveEffectivePack(packId, packs, config);
|
|
3051
|
-
|
|
3052
|
-
let res;
|
|
3053
|
-
try {
|
|
3054
|
-
res = await runLocalDeslop({
|
|
3055
|
-
text: rawText,
|
|
3056
|
-
pack,
|
|
3057
|
-
modality,
|
|
3058
|
-
register: regInfo.register,
|
|
3059
|
-
endpoint: flags.endpoint || null,
|
|
3060
|
-
model: flags.model || null,
|
|
3061
|
-
allowLan: Boolean(flags["allow-lan"]),
|
|
3062
|
-
});
|
|
3063
|
-
} catch (err) {
|
|
3064
|
-
console.error(`dislop: ${err.message}`);
|
|
3065
|
-
process.exit(2);
|
|
3066
|
-
}
|
|
3067
|
-
|
|
3068
|
-
if (!res.ok) {
|
|
3069
|
-
if (flags.json || flags.format === "json") {
|
|
3070
|
-
console.log(JSON.stringify(res, null, 2));
|
|
3071
|
-
} else {
|
|
3072
|
-
console.error(`dislop: ${res.error}`);
|
|
3073
|
-
}
|
|
3074
|
-
process.exit(2);
|
|
3075
|
-
}
|
|
3076
|
-
|
|
3077
|
-
if (flags.output) {
|
|
3078
|
-
const outAbs = path.resolve(process.cwd(), String(flags.output));
|
|
3079
|
-
fs.mkdirSync(path.dirname(outAbs), { recursive: true });
|
|
3080
|
-
fs.writeFileSync(outAbs, res.text, "utf8");
|
|
3081
|
-
}
|
|
3082
|
-
|
|
3083
|
-
if (flags.json || flags.format === "json") {
|
|
3084
|
-
console.log(JSON.stringify(res, null, 2));
|
|
3085
|
-
return;
|
|
3086
|
-
}
|
|
3087
|
-
|
|
3088
|
-
if (!flags.output) {
|
|
3089
|
-
process.stdout.write(res.text.endsWith("\n") ? res.text : res.text + "\n");
|
|
3090
|
-
} else if (lang === "zh") {
|
|
3091
|
-
console.log(
|
|
3092
|
-
`dislop 本地改写完成(${res.model}):改写 ${res.rewrittenParagraphs} 段,保留原段 ${res.keptOriginalParagraphs} 段,事实核验 ${res.factLedgerOk ? "通过" : "未通过"} -> ${flags.output}`
|
|
3093
|
-
);
|
|
3094
|
-
} else {
|
|
3095
|
-
console.log(
|
|
3096
|
-
`dislop local deslop (${res.model}): rewrote ${res.rewrittenParagraphs} paragraph(s), kept ${res.keptOriginalParagraphs} untouched, fact ledger ${res.factLedgerOk ? "ok" : "drifted"} -> ${flags.output}`
|
|
3097
|
-
);
|
|
3098
|
-
}
|
|
3099
|
-
}
|
|
3100
|
-
|
|
3101
|
-
async function runModel(args, packs, cmdAlias = "model") {
|
|
3102
|
-
const { flags, positional } = parseFlags(args, cmdAlias);
|
|
3103
|
-
if (flags.help) {
|
|
3104
|
-
printSubcommandHelp(cmdAlias);
|
|
3105
|
-
return;
|
|
3106
|
-
}
|
|
3107
|
-
const action = positional[0] || "status";
|
|
3108
|
-
const validActions = new Set(["status", "recommend", "score", "install", "setup", "import", "remove", "rm", "deslop"]);
|
|
3109
|
-
if (!validActions.has(action)) {
|
|
3110
|
-
console.error(
|
|
3111
|
-
`dislop model: unknown action '${action}' (expected status, recommend, score, install, setup, import, remove, or deslop)`
|
|
3112
|
-
);
|
|
3113
|
-
process.exit(2);
|
|
3114
|
-
}
|
|
3115
|
-
const restPos = positional.slice(1);
|
|
3116
|
-
const lang = flags.lang || "en";
|
|
3117
|
-
const asJson = Boolean(flags.json || flags.format === "json");
|
|
3118
|
-
|
|
3119
|
-
if (action === "score") {
|
|
3120
|
-
const target = restPos[0] || "-";
|
|
3121
|
-
let threshold = null;
|
|
3122
|
-
if (flags.threshold !== undefined) {
|
|
3123
|
-
threshold = Number(flags.threshold);
|
|
3124
|
-
if (typeof flags.threshold === "boolean" || String(flags.threshold).trim() === "" || !Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
|
|
3125
|
-
console.error(`dislop model score: invalid --threshold '${flags.threshold}' (expected a number between 0 and 1)`);
|
|
3126
|
-
process.exit(2);
|
|
3127
|
-
}
|
|
3128
|
-
}
|
|
3129
|
-
let rawText = "";
|
|
3130
|
-
let label = flags["stdin-filename"] || "stdin.md";
|
|
3131
|
-
if (target === "-") {
|
|
3132
|
-
rawText = fs.readFileSync(0, "utf8");
|
|
3133
|
-
} else {
|
|
3134
|
-
const abs = path.resolve(process.cwd(), target);
|
|
3135
|
-
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
3136
|
-
console.error(`dislop model score: file not found: ${target}`);
|
|
3137
|
-
process.exit(2);
|
|
3138
|
-
}
|
|
3139
|
-
label = target;
|
|
3140
|
-
rawText = decodeUtf8Strict(fs.readFileSync(abs));
|
|
3141
|
-
}
|
|
3142
|
-
const result = analyzeDocumentWithPocketModels(rawText, { threshold });
|
|
3143
|
-
if (asJson) {
|
|
3144
|
-
console.log(JSON.stringify({ file: label, ...result }, null, 2));
|
|
3145
|
-
return;
|
|
3146
|
-
}
|
|
3147
|
-
const pct = Math.round(result.documentProbability * 100);
|
|
3148
|
-
if (lang === "zh") {
|
|
3149
|
-
console.log(`dislop 内置传统模型评分(pocket-slop-v1 · 0 联网):${label}`);
|
|
3150
|
-
console.log(
|
|
3151
|
-
` 文档最高温吞水概率 : ${pct}%(阈值 ${Math.round(result.threshold * 100)}% · 命中段落 ${result.flaggedCount}/${result.paragraphs.length})`
|
|
3152
|
-
);
|
|
3153
|
-
console.log(
|
|
3154
|
-
` 自动判别场景包 : ${result.packRouter.recommendedPack}(置信度 ${Math.round(result.packRouter.confidence * 100)}%)`
|
|
3155
|
-
);
|
|
3156
|
-
for (const p of result.paragraphs) {
|
|
3157
|
-
const mark = p.flagged ? "[提醒]" : "[正常]";
|
|
3158
|
-
const drv = p.topDrivers.map((d) => d.reason.zh).join("、");
|
|
3159
|
-
console.log(` ${mark} 第 ${p.startLine}-${p.endLine} 行 (${Math.round(p.slopProbability * 100)}%)${drv ? `:${drv}` : ""}`);
|
|
3160
|
-
}
|
|
3161
|
-
} else {
|
|
3162
|
-
console.log(`dislop bundled Pocket ML score (pocket-slop-v1 · 0 network calls): ${label}`);
|
|
3163
|
-
console.log(
|
|
3164
|
-
` Max paragraph slop : ${pct}% (threshold ${Math.round(result.threshold * 100)}% · flagged ${result.flaggedCount}/${result.paragraphs.length})`
|
|
3165
|
-
);
|
|
3166
|
-
console.log(
|
|
3167
|
-
` Recommended pack : ${result.packRouter.recommendedPack} (confidence ${Math.round(result.packRouter.confidence * 100)}%)`
|
|
3168
|
-
);
|
|
3169
|
-
for (const p of result.paragraphs) {
|
|
3170
|
-
const mark = p.flagged ? "[FLAG]" : "[OK] ";
|
|
3171
|
-
const drv = p.topDrivers.map((d) => d.reason.en).join("; ");
|
|
3172
|
-
console.log(` ${mark} lines ${p.startLine}-${p.endLine} (${Math.round(p.slopProbability * 100)}%)${drv ? ` — ${drv}` : ""}`);
|
|
3173
|
-
}
|
|
3174
|
-
}
|
|
3175
|
-
return;
|
|
3176
|
-
}
|
|
3177
|
-
|
|
3178
|
-
if ( action === "install" || action === "setup" ) {
|
|
3179
|
-
let rulesCount = 0;
|
|
3180
|
-
for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
|
|
3181
|
-
const status = await buildModelStatusReport({
|
|
3182
|
-
packsCount: Object.keys(packs).length,
|
|
3183
|
-
rulesCount,
|
|
3184
|
-
probeLoopback: false,
|
|
3185
|
-
cacheDir: flags["cache-dir"] || null,
|
|
3186
|
-
});
|
|
3187
|
-
let chosenTier = flags.tier || null;
|
|
3188
|
-
if (!chosenTier) {
|
|
3189
|
-
if (action === "setup" && process.stdin.isTTY && !flags.yes && !asJson && !flags["dry-run"]) {
|
|
3190
|
-
if (lang === "zh") {
|
|
3191
|
-
console.log(`dislop 模型选装向导(内置 15 KB 传统集成模型已就绪)`);
|
|
3192
|
-
console.log(` 硬件检测:${status.hardware.platform}/${status.hardware.arch} · ${status.hardware.totalMemoryGb} GB 内存 · 推荐档位 ${status.recommendation.tier}`);
|
|
3193
|
-
for (const t of Object.values(LOCAL_MODEL_TIERS)) {
|
|
3194
|
-
console.log(` - ${t.tier.padEnd(9)} (${String(t.approxDownloadMb).padStart(4)} MB): ${t.summary.zh}`);
|
|
3195
|
-
}
|
|
3196
|
-
} else {
|
|
3197
|
-
console.log(`dislop optional model setup (bundled 15 KB Pocket ML is already active)`);
|
|
3198
|
-
console.log(` Hardware: ${status.hardware.platform}/${status.hardware.arch} · ${status.hardware.totalMemoryGb} GB RAM · recommended '${status.recommendation.tier}'`);
|
|
3199
|
-
for (const t of Object.values(LOCAL_MODEL_TIERS)) {
|
|
3200
|
-
console.log(` - ${t.tier.padEnd(9)} (${String(t.approxDownloadMb).padStart(4)} MB): ${t.summary.en}`);
|
|
3201
|
-
}
|
|
3202
|
-
}
|
|
3203
|
-
chosenTier = await promptInteractiveTier(status.recommendation.tier, lang);
|
|
3204
|
-
} else {
|
|
3205
|
-
chosenTier = restPos[0] || "auto";
|
|
3206
|
-
}
|
|
3207
|
-
}
|
|
3208
|
-
|
|
3209
|
-
const res = installOptionalModel({
|
|
3210
|
-
tier: chosenTier,
|
|
3211
|
-
provider: flags.provider || "ollama",
|
|
3212
|
-
force: Boolean(flags.force),
|
|
3213
|
-
dryRun: Boolean(flags["dry-run"]),
|
|
3214
|
-
cacheDir: flags["cache-dir"] || null,
|
|
3215
|
-
});
|
|
3216
|
-
|
|
3217
|
-
if (asJson) {
|
|
3218
|
-
console.log(JSON.stringify(res, null, 2));
|
|
3219
|
-
if (!res.ok) process.exit(res.blockedByHardware ? 1 : 2);
|
|
3220
|
-
return;
|
|
3221
|
-
}
|
|
3222
|
-
|
|
3223
|
-
if (!res.ok) {
|
|
3224
|
-
const msg = res.warning?.[lang] || res.message?.[lang] || res.warning?.en || res.message?.en || res.error;
|
|
3225
|
-
console.error(`dislop model install: ${msg}`);
|
|
3226
|
-
process.exit(res.blockedByHardware ? 1 : 2);
|
|
3227
|
-
}
|
|
3228
|
-
if (res.dryRun) {
|
|
3229
|
-
console.log(
|
|
3230
|
-
lang === "zh"
|
|
3231
|
-
? `dislop 选装预检通过:档位 ${res.tier} (${res.modelId || res.provider}, 约 ${res.approxDownloadMb || 0} MB) -> ${res.command || res.modelCacheDir}`
|
|
3232
|
-
: `dislop install dry-run passed: tier '${res.tier}' (${res.modelId || res.provider}, ~${res.approxDownloadMb || 0} MB) -> ${res.command || res.modelCacheDir}`
|
|
3233
|
-
);
|
|
3234
|
-
return;
|
|
3235
|
-
}
|
|
3236
|
-
const doneMsg = res.message?.[lang] || res.message?.en || `Installed tier '${res.tier}' (${res.modelId}).`;
|
|
3237
|
-
console.log(doneMsg);
|
|
3238
|
-
return;
|
|
3239
|
-
}
|
|
3240
|
-
|
|
3241
|
-
if (action === "import") {
|
|
3242
|
-
const fileArg = restPos[0];
|
|
3243
|
-
if (!fileArg) {
|
|
3244
|
-
console.error("Usage: dislop model import <file.gguf|file.onnx> [--tier <tier>] [--sha256 <hex>] [--no-copy] [--json]");
|
|
3245
|
-
process.exit(2);
|
|
3246
|
-
}
|
|
3247
|
-
const res = importLocalModelFile({
|
|
3248
|
-
filePath: fileArg,
|
|
3249
|
-
tier: flags.tier || "custom",
|
|
3250
|
-
expectedSha256: flags.sha256 || null,
|
|
3251
|
-
copyFile: !flags["no-copy"],
|
|
3252
|
-
cacheDir: flags["cache-dir"] || null,
|
|
3253
|
-
});
|
|
3254
|
-
if (asJson) {
|
|
3255
|
-
console.log(JSON.stringify(res, null, 2));
|
|
3256
|
-
if (!res.ok) process.exit(2);
|
|
3257
|
-
return;
|
|
3258
|
-
}
|
|
3259
|
-
if (!res.ok) {
|
|
3260
|
-
console.error(`dislop model import: ${res.error}`);
|
|
3261
|
-
process.exit(2);
|
|
3262
|
-
}
|
|
3263
|
-
console.log(`Imported ${res.imported.id} (tier=${res.imported.tier}, sha256=${res.imported.sha256.slice(0, 12)}…) -> ${res.imported.path}`);
|
|
3264
|
-
return;
|
|
3265
|
-
}
|
|
3266
|
-
|
|
3267
|
-
if (action === "remove" || action === "rm") {
|
|
3268
|
-
const target = restPos[0] || flags.tier;
|
|
3269
|
-
const res = removeInstalledModel({ target, cacheDir: flags["cache-dir"] || null });
|
|
3270
|
-
if (asJson) {
|
|
3271
|
-
console.log(JSON.stringify(res, null, 2));
|
|
3272
|
-
if (!res.ok) process.exit(1);
|
|
3273
|
-
return;
|
|
3274
|
-
}
|
|
3275
|
-
if (!res.ok) {
|
|
3276
|
-
console.error(`dislop model remove: ${res.error || `no cached model matched '${target}'`}`);
|
|
3277
|
-
process.exit(1);
|
|
3278
|
-
}
|
|
3279
|
-
console.log(`Removed ${res.removedCount} cached model entry(s).`);
|
|
3280
|
-
return;
|
|
3281
|
-
}
|
|
3282
|
-
|
|
3283
|
-
if (action === "deslop") {
|
|
3284
|
-
await runLocalDeslopCli(restPos[0] || "-", flags, packs);
|
|
3285
|
-
return;
|
|
3286
|
-
}
|
|
3287
|
-
|
|
3288
|
-
let rulesCount = 0;
|
|
3289
|
-
for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
|
|
3290
|
-
const report = await buildModelStatusReport({
|
|
3291
|
-
packsCount: Object.keys(packs).length,
|
|
3292
|
-
rulesCount,
|
|
3293
|
-
probeLoopback: !flags["no-loopback"],
|
|
3294
|
-
cacheDir: flags["cache-dir"] || null,
|
|
3295
|
-
});
|
|
3296
|
-
|
|
3297
|
-
if (asJson) {
|
|
3298
|
-
console.log(JSON.stringify(report, null, 2));
|
|
3299
|
-
return;
|
|
3300
|
-
}
|
|
3301
|
-
|
|
3302
|
-
const hw = report.hardware;
|
|
3303
|
-
const rec = report.recommendation;
|
|
3304
|
-
const bm = report.bundledModels?.[0];
|
|
3305
|
-
if (lang === "zh") {
|
|
3306
|
-
console.log(`dislop 本地引擎、随包传统模型与选装小模型状态(检查全程 0 联网)`);
|
|
3307
|
-
console.log(` 内置确定性引擎 : 已就绪(${report.builtinDeterministic.bundledPacks} 套规则包 / ${report.builtinDeterministic.bundledRules} 条规则全量内置)`);
|
|
3308
|
-
if (bm) {
|
|
3309
|
-
console.log(` 随包传统模型 : 已内置 ${bm.id}(约 ${bm.approxGzipKb} KB gz · 含隐蔽水文集成评分与场景自动路由)`);
|
|
3310
|
-
}
|
|
3311
|
-
console.log(` 当前机器硬件 : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB 内存${hw.freeDiskGb !== null ? ` · 剩余磁盘 ${hw.freeDiskGb} GB` : ""}`);
|
|
3312
|
-
console.log(` 可选生成小模型 : ${rec.tier}${rec.modelId ? ` (${rec.modelId}, 约 ${rec.approxDownloadMb} MB)` : "(无需额外下载)"}`);
|
|
3313
|
-
console.log(` 说明 : ${rec.reason.zh}`);
|
|
3314
|
-
if (rec.installHint) console.log(` 按需选装命令 : ${rec.installHint}`);
|
|
3315
|
-
if (report.installedModels.length > 0) {
|
|
3316
|
-
console.log(` 已装本地权重 : ${report.installedModels.map((m) => `${m.id}[${m.tier}]`).join(", ")}`);
|
|
3317
|
-
}
|
|
3318
|
-
if (report.localRunners.length > 0) {
|
|
3319
|
-
for (const r of report.localRunners) {
|
|
3320
|
-
console.log(` 已发现本地服务 : ${r.kind} (${r.endpoint}) -> ${r.models.join(", ") || "无已装模型"}`);
|
|
3321
|
-
}
|
|
3322
|
-
}
|
|
3323
|
-
} else {
|
|
3324
|
-
console.log(`dislop local engine, bundled ML & optional model status (0 external network calls)`);
|
|
3325
|
-
console.log(` Built-in engine : ready (${report.builtinDeterministic.bundledPacks} packs / ${report.builtinDeterministic.bundledRules} rules bundled offline)`);
|
|
3326
|
-
if (bm) {
|
|
3327
|
-
console.log(` Bundled ML : ready (${bm.id}, ~${bm.approxGzipKb} KB gz · paragraph slop ensemble + domain router)`);
|
|
3328
|
-
}
|
|
3329
|
-
console.log(` Hardware : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB RAM${hw.freeDiskGb !== null ? ` · ${hw.freeDiskGb} GB free disk` : ""}`);
|
|
3330
|
-
console.log(` Recommended SLM : ${rec.tier}${rec.modelId ? ` (${rec.modelId}, ~${rec.approxDownloadMb} MB)` : " (no extra download needed)"}`);
|
|
3331
|
-
console.log(` Reason : ${rec.reason.en}`);
|
|
3332
|
-
if (rec.installHint) console.log(` Optional install: ${rec.installHint}`);
|
|
3333
|
-
if (report.installedModels.length > 0) {
|
|
3334
|
-
console.log(` Cached weights : ${report.installedModels.map((m) => `${m.id}[${m.tier}]`).join(", ")}`);
|
|
3335
|
-
}
|
|
3336
|
-
if (report.localRunners.length > 0) {
|
|
3337
|
-
for (const r of report.localRunners) {
|
|
3338
|
-
console.log(` Active loopback : ${r.kind} (${r.endpoint}) -> ${r.models.join(", ") || "no models loaded"}`);
|
|
3339
|
-
}
|
|
3340
|
-
}
|
|
3341
|
-
}
|
|
3342
|
-
}
|
|
3343
|
-
|
|
3344
|
-
function readGitBaselineForFile(absFile, gitRef = "HEAD") {
|
|
3345
|
-
const fileDir = path.dirname(absFile);
|
|
3346
|
-
const topLevel = execFileSync("git", ["-c", "core.quotepath=off", "rev-parse", "--show-toplevel"], {
|
|
3347
|
-
cwd: fileDir,
|
|
3348
|
-
encoding: "utf8",
|
|
3349
|
-
}).trim();
|
|
3350
|
-
const realFile = fs.realpathSync(absFile);
|
|
3351
|
-
const realTop = fs.realpathSync(topLevel);
|
|
3352
|
-
const relPosix = path.relative(realTop, realFile).split(path.sep).join("/");
|
|
3353
|
-
return execFileSync("git", ["-c", "core.quotepath=off", "show", `${gitRef}:${relPosix}`], {
|
|
3354
|
-
cwd: realTop,
|
|
3355
|
-
encoding: "utf8",
|
|
3356
|
-
maxBuffer: 32 * 1024 * 1024,
|
|
3357
|
-
});
|
|
3358
|
-
}
|
|
3359
|
-
|
|
3360
|
-
function runVerify(args, packs) {
|
|
3361
|
-
const { flags, positional } = parseFlags(args, "verify");
|
|
3362
|
-
if (flags.help) {
|
|
3363
|
-
printSubcommandHelp("verify");
|
|
3364
|
-
return;
|
|
3365
|
-
}
|
|
3366
|
-
const cwd = process.cwd();
|
|
3367
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
3368
|
-
assertTextOrJsonFormat(format);
|
|
3369
|
-
const lang = flags.lang || "en";
|
|
3370
|
-
if (!["en", "zh"].includes(lang)) {
|
|
3371
|
-
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
3372
|
-
process.exit(2);
|
|
3373
|
-
}
|
|
3374
|
-
const allowAdded = Boolean(flags["allow-added"]);
|
|
3375
|
-
const strict = Boolean(flags.strict);
|
|
3376
|
-
let flagRegister = null;
|
|
3377
|
-
if (flags.register !== undefined) {
|
|
3378
|
-
const norm = String(flags.register).trim().toLowerCase();
|
|
3379
|
-
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
3380
|
-
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
3381
|
-
process.exit(2);
|
|
3382
|
-
}
|
|
3383
|
-
flagRegister = norm;
|
|
3384
|
-
}
|
|
3385
|
-
const keepRaw = typeof flags.keep === "string" ? flags.keep : "";
|
|
3386
|
-
const keepTerms = keepRaw ? keepRaw.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
3387
|
-
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
3388
|
-
|
|
3389
|
-
let beforeText;
|
|
3390
|
-
let afterText;
|
|
3391
|
-
let label;
|
|
3392
|
-
if (flags.git !== undefined) {
|
|
3393
|
-
let gitRef = "HEAD";
|
|
3394
|
-
let targetPath;
|
|
3395
|
-
if (flags.git === true) {
|
|
3396
|
-
targetPath = positional[0];
|
|
3397
|
-
} else if (positional.length === 0) {
|
|
3398
|
-
targetPath = String(flags.git);
|
|
3399
|
-
} else {
|
|
3400
|
-
gitRef = String(flags.git);
|
|
3401
|
-
targetPath = positional[0];
|
|
3402
|
-
}
|
|
3403
|
-
if (!targetPath) {
|
|
3404
|
-
console.error("Usage: dislop verify --git [ref] <file> [--keep a,b] [--pack <id|auto>] [--strict] [--json]");
|
|
3405
|
-
process.exit(2);
|
|
3406
|
-
}
|
|
3407
|
-
const absTarget = path.resolve(cwd, targetPath);
|
|
3408
|
-
if (!fs.existsSync(absTarget) || !fs.statSync(absTarget).isFile()) {
|
|
3409
|
-
console.error(`dislop: file not found: ${targetPath}`);
|
|
3410
|
-
process.exit(2);
|
|
3411
|
-
}
|
|
3412
|
-
label = targetPath;
|
|
3413
|
-
afterText = decodeUtf8Strict(fs.readFileSync(absTarget));
|
|
3414
|
-
try {
|
|
3415
|
-
beforeText = readGitBaselineForFile(absTarget, gitRef);
|
|
3416
|
-
} catch (err) {
|
|
3417
|
-
console.error(`dislop verify: failed to read '${gitRef}' baseline for '${targetPath}': ${err.message}`);
|
|
3418
|
-
process.exit(2);
|
|
3419
|
-
}
|
|
3420
|
-
} else {
|
|
3421
|
-
if (positional.length < 2) {
|
|
3422
|
-
console.error("Usage: dislop verify <before-file> <after-file> [--keep a,b] [--pack <id|auto>] [--strict] [--json]");
|
|
3423
|
-
process.exit(2);
|
|
3424
|
-
}
|
|
3425
|
-
const beforeAbs = path.resolve(cwd, positional[0]);
|
|
3426
|
-
const afterAbs = path.resolve(cwd, positional[1]);
|
|
3427
|
-
for (const [p, rawArg] of [[beforeAbs, positional[0]], [afterAbs, positional[1]]]) {
|
|
3428
|
-
if (!fs.existsSync(p) || !fs.statSync(p).isFile()) {
|
|
3429
|
-
console.error(`dislop: file not found: ${rawArg}`);
|
|
3430
|
-
process.exit(2);
|
|
3431
|
-
}
|
|
3432
|
-
}
|
|
3433
|
-
label = positional[1];
|
|
3434
|
-
beforeText = decodeUtf8Strict(fs.readFileSync(beforeAbs));
|
|
3435
|
-
afterText = decodeUtf8Strict(fs.readFileSync(afterAbs));
|
|
3436
|
-
}
|
|
3437
|
-
|
|
3438
|
-
const mod = detectModality(label) || "markdown";
|
|
3439
|
-
const fileCfg = resolveConfigForFile(label, config);
|
|
3440
|
-
let resolvedPack;
|
|
3441
|
-
try {
|
|
3442
|
-
resolvedPack = resolveTextPackAndSource(afterText, label, mod, flags.pack || "auto", fileCfg, packs);
|
|
3443
|
-
} catch (err) {
|
|
3444
|
-
console.error(`dislop: ${err.message}`);
|
|
3445
|
-
process.exit(2);
|
|
3446
|
-
}
|
|
3447
|
-
const result = verifyRevisionBundle(beforeText, afterText, {
|
|
3448
|
-
filename: label,
|
|
3449
|
-
modality: mod,
|
|
3450
|
-
pack: resolvedPack.pack,
|
|
3451
|
-
config: fileCfg,
|
|
3452
|
-
register: flagRegister,
|
|
3453
|
-
keepTerms,
|
|
3454
|
-
allowAdded,
|
|
3455
|
-
strict,
|
|
3456
|
-
});
|
|
3457
|
-
result.effectivePack = resolvedPack.effectivePack;
|
|
3458
|
-
result.packSource = resolvedPack.packSource;
|
|
3459
|
-
|
|
3460
|
-
if (format === "json") {
|
|
3461
|
-
console.log(JSON.stringify(result, null, 2));
|
|
3462
|
-
} else {
|
|
3463
|
-
const fl = result.factLedger;
|
|
3464
|
-
const lc = result.lengthCheck;
|
|
3465
|
-
const ad = result.antiDegradation;
|
|
3466
|
-
if (lang === "zh") {
|
|
3467
|
-
console.log(`dislop verify (${label}): ${result.ok ? "通过 (PASSED)" : "未通过 (FAILED)"}`);
|
|
3468
|
-
console.log(` 事实账本 : ${fl.status}(保留 ${fl.retainedCount}/${fl.totalProtected},丢失 ${fl.missing.length},限定词降级 ${fl.qualifierDropped.length})`);
|
|
3469
|
-
if (result.keepTerms.requested.length > 0) {
|
|
3470
|
-
console.log(` 关键词保留: 保留 ${result.keepTerms.kept.length}/${result.keepTerms.requested.length}${result.keepTerms.missing.length ? `(缺失:${result.keepTerms.missing.join(", ")})` : ""}`);
|
|
3471
|
-
}
|
|
3472
|
-
if (result.findingsDelta) {
|
|
3473
|
-
console.log(` AI味变化 : ${result.findingsDelta.beforeCount} -> ${result.findingsDelta.afterCount}(消解 ${result.findingsDelta.resolvedCount},新引入 ${result.findingsDelta.introduced.length})`);
|
|
3474
|
-
}
|
|
3475
|
-
console.log(` 篇幅比例 : ${lc.beforeChars} -> ${lc.afterChars} 字(${lc.ratio}x · ${lc.status})`);
|
|
3476
|
-
console.log(` 反退化校验: ${ad.status}`);
|
|
3477
|
-
for (const w of ad.warnings) {
|
|
3478
|
-
console.log(` - [${w.severity.toUpperCase()}] ${w.code}: ${w.message.zh}`);
|
|
3479
|
-
}
|
|
3480
|
-
} else {
|
|
3481
|
-
console.log(`dislop verify (${label}): ${result.status.toUpperCase()}`);
|
|
3482
|
-
console.log(` Fact ledger : ${fl.status} (${fl.retainedCount}/${fl.totalProtected} retained, ${fl.missing.length} missing, ${fl.qualifierDropped.length} qualifier dropped)`);
|
|
3483
|
-
if (result.keepTerms.requested.length > 0) {
|
|
3484
|
-
console.log(` Keep terms : ${result.keepTerms.kept.length}/${result.keepTerms.requested.length} kept${result.keepTerms.missing.length ? ` (missing: ${result.keepTerms.missing.join(", ")})` : ""}`);
|
|
3485
|
-
}
|
|
3486
|
-
if (result.findingsDelta) {
|
|
3487
|
-
console.log(` Findings delta: ${result.findingsDelta.beforeCount} -> ${result.findingsDelta.afterCount} (${result.findingsDelta.resolvedCount} resolved, ${result.findingsDelta.introduced.length} introduced)`);
|
|
3488
|
-
}
|
|
3489
|
-
console.log(` Length ratio : ${lc.beforeChars} -> ${lc.afterChars} chars (${lc.ratio}x · ${lc.status})`);
|
|
3490
|
-
console.log(` Anti-degrade : ${ad.status}`);
|
|
3491
|
-
for (const w of ad.warnings) {
|
|
3492
|
-
console.log(` - [${w.severity.toUpperCase()}] ${w.code}: ${w.message.en}`);
|
|
3493
|
-
}
|
|
3494
|
-
}
|
|
3495
|
-
}
|
|
3496
|
-
process.exitCode = result.ok ? 0 : 1;
|
|
3497
|
-
}
|
|
3498
|
-
|
|
3499
|
-
const REVIEW_RESLOP_ZH_RE = /(?:全闭环|闭环|严禁|杜绝|赋能|抓手|家人们|绝绝子|其实吧|咱就是说|不是[^。\n]{1,30}而是)/g;
|
|
3500
|
-
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;
|
|
3501
|
-
const VALID_TIC_LAYERS = new Set(["lexical", "syntactic", "rhythm", "cognitive-framing", "rhetorical-stance", "visual", "artifact"]);
|
|
3502
|
-
|
|
3503
|
-
function loadAiTicRubric(customPatternsDir = PATTERNS_DIR) {
|
|
3504
|
-
const p = path.join(customPatternsDir, "ai-tic-rubric.json");
|
|
3505
|
-
try {
|
|
3506
|
-
if (fs.existsSync(p)) {
|
|
3507
|
-
return JSON.parse(fs.readFileSync(p, "utf8"));
|
|
3508
|
-
}
|
|
3509
|
-
} catch {}
|
|
3510
|
-
return { layers: [], antiDegradationPrinciples: { en: [], zh: [] } };
|
|
3511
|
-
}
|
|
3512
|
-
|
|
3513
|
-
function mapFindingToTicLayer(finding) {
|
|
3514
|
-
const rid = String(finding?.ruleId || "");
|
|
3515
|
-
const dim = String(finding?.dimension || "");
|
|
3516
|
-
const fam = String(finding?.family || "");
|
|
3517
|
-
if (rid.startsWith("core/") || fam.startsWith("hygiene/") || fam.startsWith("office/") || dim === "artifacts") return "artifact";
|
|
3518
|
-
if (rid.startsWith("ui-") || rid.startsWith("pptx-") || fam.startsWith("deck/") || fam.startsWith("ui/") || dim === "visual-and-deck") return "visual";
|
|
3519
|
-
if (
|
|
3520
|
-
dim === "rhythm" ||
|
|
3521
|
-
fam.startsWith("rhythm/") ||
|
|
3522
|
-
fam.startsWith("punctuation/") ||
|
|
3523
|
-
["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)
|
|
3524
|
-
) {
|
|
3525
|
-
return "rhythm";
|
|
3526
|
-
}
|
|
3527
|
-
if (
|
|
3528
|
-
dim === "syntactic" ||
|
|
3529
|
-
fam.startsWith("frame/") ||
|
|
3530
|
-
["negation-pivot", "staccato-slogan-run", "zh-four-char-triad", "concession-symmetry-frame", "rhetorical-qa-cadence", "pull-quote-closer", "template-skeleton-echo"].includes(rid)
|
|
3531
|
-
) {
|
|
3532
|
-
return "syntactic";
|
|
3533
|
-
}
|
|
3534
|
-
if (
|
|
3535
|
-
["macro-trend-opener", "moralizing-ending", "narrative-sandwich", "unsourced-attribution", "unsubstantiated-superlative", "composite-multi-signal"].includes(rid) ||
|
|
3536
|
-
fam.startsWith("evidence/")
|
|
3537
|
-
) {
|
|
3538
|
-
return "cognitive-framing";
|
|
3539
|
-
}
|
|
3540
|
-
if (["throat-clearing-opener", "sycophancy-residue", "hedge-cluster", "discourse-marker-cluster"].includes(rid) || dim === "discourse") {
|
|
3541
|
-
return "rhetorical-stance";
|
|
3542
|
-
}
|
|
3543
|
-
return "lexical";
|
|
3544
|
-
}
|
|
3545
|
-
|
|
3546
|
-
function buildCrossCheckSummary({ ruleFindings, patternFindings, profile, mlFindings, mergedFindings, modality }) {
|
|
3547
|
-
const signalsPresent = [];
|
|
3548
|
-
if (ruleFindings.length > 0) signalsPresent.push("rules");
|
|
3549
|
-
if (patternFindings.length > 0) signalsPresent.push("patterns");
|
|
3550
|
-
if (profile && ((profile.telemetryRisk?.score || 0) >= 15 || profile.structure?.lowBurstinessVapor)) {
|
|
3551
|
-
signalsPresent.push("profile");
|
|
3552
|
-
}
|
|
3553
|
-
if (mlFindings.length > 0) signalsPresent.push("pocket-ml");
|
|
3554
|
-
|
|
3555
|
-
const layerCounts = {};
|
|
3556
|
-
for (const f of mergedFindings) {
|
|
3557
|
-
const layer = mapFindingToTicLayer(f);
|
|
3558
|
-
layerCounts[layer] = (layerCounts[layer] || 0) + 1;
|
|
3559
|
-
}
|
|
3560
|
-
|
|
3561
|
-
const proseMods = new Set(["markdown", "text", "html", "svg"]);
|
|
3562
|
-
const hasSubtleProse = Boolean(proseMods.has(modality) && profile && (profile.sentenceCount || 0) >= 3);
|
|
3563
|
-
const suspectedSubtleLayers = hasSubtleProse && (signalsPresent.length > 0 || ruleFindings.length === 0)
|
|
3564
|
-
? ["cognitive-framing", "rhetorical-stance"]
|
|
3565
|
-
: [];
|
|
3566
|
-
const llmRecommended = Boolean(
|
|
3567
|
-
hasSubtleProse && ((profile.telemetryRisk?.score || 0) >= 15 || mlFindings.length > 0 || ruleFindings.length === 0)
|
|
3568
|
-
);
|
|
3569
|
-
|
|
3570
|
-
return {
|
|
3571
|
-
signalsPresent,
|
|
3572
|
-
multiSignalConfirmed: signalsPresent.length >= 2,
|
|
3573
|
-
layerCounts,
|
|
3574
|
-
suspectedSubtleLayers,
|
|
3575
|
-
llmRecommended,
|
|
3576
|
-
};
|
|
3577
|
-
}
|
|
3578
|
-
|
|
3579
|
-
function findingsToReviewIssues(findings, lang = "en") {
|
|
3580
|
-
return findings.map((f) => {
|
|
3581
|
-
const strategy = f.fixStrategy || deriveFixStrategy({ id: f.ruleId, family: f.family });
|
|
3582
|
-
const action = strategy === "delete" ? "edit" : strategy === "need-source" ? "ask" : "rewrite";
|
|
3583
|
-
const why = (f.message?.[lang] || f.message?.en || f.ruleId || "").trim();
|
|
3584
|
-
const guidance = (f.deletionTest?.[lang] || f.deletionTest?.en || why).trim();
|
|
3585
|
-
const issue = {
|
|
3586
|
-
source: f.source || "rule",
|
|
3587
|
-
ruleId: f.ruleId,
|
|
3588
|
-
ticLayer: mapFindingToTicLayer(f),
|
|
3589
|
-
severity: f.severity,
|
|
3590
|
-
fixStrategy: strategy,
|
|
3591
|
-
action,
|
|
3592
|
-
line: f.line || 1,
|
|
3593
|
-
col: f.col || 1,
|
|
3594
|
-
quote: f.match || "",
|
|
3595
|
-
why,
|
|
3596
|
-
...(action === "edit"
|
|
3597
|
-
? { replacement: "" }
|
|
3598
|
-
: action === "ask"
|
|
3599
|
-
? { question: guidance }
|
|
3600
|
-
: { instruction: guidance }),
|
|
3601
|
-
};
|
|
3602
|
-
if (action === "edit" && f.span && f.span.end - f.span.start === codePointLength(issue.quote)) {
|
|
3603
|
-
issue.edit = { start: f.span.start, before: issue.quote, after: "" };
|
|
3604
|
-
}
|
|
3605
|
-
return issue;
|
|
3606
|
-
});
|
|
3607
|
-
}
|
|
3608
|
-
|
|
3609
|
-
function groundByokLlmIssues(rawIssues, sourceText, lineStarts) {
|
|
3610
|
-
if (!Array.isArray(rawIssues)) return [];
|
|
3611
|
-
const src = String(sourceText || "");
|
|
3612
|
-
const out = [];
|
|
3613
|
-
for (const iss of rawIssues) {
|
|
3614
|
-
if (!iss || typeof iss !== "object") continue;
|
|
3615
|
-
const q = String(iss.quote || "").trim();
|
|
3616
|
-
if (!q) continue;
|
|
3617
|
-
const idx = src.indexOf(q);
|
|
3618
|
-
if (idx === -1) continue;
|
|
3619
|
-
let action = ["edit", "replace", "delete", "rewrite", "ask"].includes(iss.action) ? iss.action : "rewrite";
|
|
3620
|
-
if (action === "replace" || action === "delete") action = "edit";
|
|
3621
|
-
if (action === "edit" && iss.action !== "delete" && typeof iss.replacement !== "string") action = "rewrite";
|
|
3622
|
-
const rep = action === "edit" && iss.action !== "delete" ? iss.replacement : "";
|
|
3623
|
-
if (action === "edit" || iss.replacement) {
|
|
3624
|
-
let introducedSlop = false;
|
|
3625
|
-
const qLower = q.toLowerCase();
|
|
3626
|
-
for (const m of String(iss.replacement || "").matchAll(REVIEW_RESLOP_ZH_RE)) {
|
|
3627
|
-
if (!q.includes(m[0])) {
|
|
3628
|
-
introducedSlop = true;
|
|
3629
|
-
break;
|
|
3630
|
-
}
|
|
3631
|
-
}
|
|
3632
|
-
if (!introducedSlop) {
|
|
3633
|
-
for (const m of String(iss.replacement || "").matchAll(REVIEW_RESLOP_EN_RE)) {
|
|
3634
|
-
if (!qLower.includes(m[0].toLowerCase())) {
|
|
3635
|
-
introducedSlop = true;
|
|
3636
|
-
break;
|
|
3637
|
-
}
|
|
3638
|
-
}
|
|
3639
|
-
}
|
|
3640
|
-
if (introducedSlop) continue;
|
|
3641
|
-
}
|
|
3642
|
-
let finalInstruction = String(iss.instruction || iss.why || "").trim();
|
|
3643
|
-
if (action === "edit") {
|
|
3644
|
-
const vr = verifyRevision(q, rep);
|
|
3645
|
-
if (vr.status !== "preserved") {
|
|
3646
|
-
action = "rewrite";
|
|
3647
|
-
if (!finalInstruction) finalInstruction = String(iss.why || "Keep all numbers and qualifiers intact while removing filler.");
|
|
3648
|
-
}
|
|
3649
|
-
}
|
|
3650
|
-
const lc = lineStarts ? (() => {
|
|
3651
|
-
let lo = 0; let hi = lineStarts.length - 1;
|
|
3652
|
-
while (lo <= hi) { const mid = (lo + hi) >> 1; if (lineStarts[mid] <= idx) lo = mid + 1; else hi = mid - 1; }
|
|
3653
|
-
const li = Math.max(0, hi);
|
|
3654
|
-
return { line: li + 1, col: codePointLength(src.slice(lineStarts[li], idx)) + 1 };
|
|
3655
|
-
})() : { line: 1, col: 1 };
|
|
3656
|
-
const issue = {
|
|
3657
|
-
source: "byok-llm",
|
|
3658
|
-
ruleId: null,
|
|
3659
|
-
...(VALID_TIC_LAYERS.has(iss.ticLayer) ? { ticLayer: iss.ticLayer } : {}),
|
|
3660
|
-
severity: ["error", "warning", "info"].includes(iss.severity) ? iss.severity : "warning",
|
|
3661
|
-
fixStrategy: action === "edit" ? (rep === "" ? "delete" : "rephrase") : action === "ask" ? "need-source" : "rephrase",
|
|
3662
|
-
action,
|
|
3663
|
-
line: lc.line,
|
|
3664
|
-
col: lc.col,
|
|
3665
|
-
quote: q,
|
|
3666
|
-
why: String(iss.why || "").trim(),
|
|
3667
|
-
...(action === "edit"
|
|
3668
|
-
? { replacement: rep }
|
|
3669
|
-
: action === "ask"
|
|
3670
|
-
? { question: String(iss.question || finalInstruction).trim() }
|
|
3671
|
-
: { instruction: finalInstruction }),
|
|
3672
|
-
};
|
|
3673
|
-
if (action === "edit" && idx === src.lastIndexOf(q)) {
|
|
3674
|
-
issue.edit = { start: codePointLength(src.slice(0, idx)), before: q, after: rep };
|
|
3675
|
-
}
|
|
3676
|
-
out.push(issue);
|
|
3677
|
-
if (out.length >= 16) break;
|
|
3678
|
-
}
|
|
3679
|
-
return out;
|
|
3680
|
-
}
|
|
3681
|
-
|
|
3682
|
-
function buildRubricPromptDigest(rubric, lang = "en") {
|
|
3683
|
-
const isZh = lang === "zh";
|
|
3684
|
-
const layers = Array.isArray(rubric?.layers) ? rubric.layers : [];
|
|
3685
|
-
if (layers.length === 0) return "";
|
|
3686
|
-
return layers
|
|
3687
|
-
.map((layer) => {
|
|
3688
|
-
const name = layer.name?.[isZh ? "zh" : "en"] || layer.id;
|
|
3689
|
-
const prompt = layer.llmCheckPrompt?.[isZh ? "zh" : "en"] || "";
|
|
3690
|
-
const guards = (layer.falsePositiveGuards?.[isZh ? "zh" : "en"] || []).slice(0, 1).join("; ");
|
|
3691
|
-
return `- [${layer.id}] ${name}: ${prompt}${guards ? ` (Guard: ${guards})` : ""}`;
|
|
3692
|
-
})
|
|
3693
|
-
.join("\n");
|
|
3694
|
-
}
|
|
3695
|
-
|
|
3696
|
-
async function runRubricReview(flags, positional, packs) {
|
|
3697
|
-
const cwd = process.cwd();
|
|
3698
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
3699
|
-
assertTextOrJsonFormat(format);
|
|
3700
|
-
const lang = flags.lang || "en";
|
|
3701
|
-
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
3702
|
-
const voiceInfo = discoverVoiceCard(cwd);
|
|
3703
|
-
const rubric = loadAiTicRubric();
|
|
3704
|
-
const target = positional[0] || "-";
|
|
3705
|
-
|
|
3706
|
-
let text;
|
|
3707
|
-
let label;
|
|
3708
|
-
if (target === "-") {
|
|
3709
|
-
text = readStdinTextChecked("review");
|
|
3710
|
-
label = detectStdinFilename(text, flags["stdin-filename"]);
|
|
3711
|
-
} else {
|
|
3712
|
-
const abs = path.resolve(cwd, target);
|
|
3713
|
-
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
3714
|
-
console.error(`dislop: file not found: ${target}`);
|
|
3715
|
-
process.exit(2);
|
|
3716
|
-
}
|
|
3717
|
-
label = target;
|
|
3718
|
-
text = decodeUtf8Strict(fs.readFileSync(abs));
|
|
3719
|
-
}
|
|
3720
|
-
|
|
3721
|
-
const mod = detectModality(label) || "markdown";
|
|
3722
|
-
const fileCfg = resolveConfigForFile(label, config);
|
|
3723
|
-
let flagRegister = null;
|
|
3724
|
-
if (flags.register !== undefined) {
|
|
3725
|
-
const norm = String(flags.register).trim().toLowerCase();
|
|
3726
|
-
if (!norm || (norm !== "auto" && !VALID_REGISTERS.includes(norm))) {
|
|
3727
|
-
console.error(`dislop: invalid --register '${flags.register}' (expected auto, ${VALID_REGISTERS.join(", ")})`);
|
|
3728
|
-
process.exit(2);
|
|
3729
|
-
}
|
|
3730
|
-
flagRegister = norm;
|
|
3731
|
-
}
|
|
3732
|
-
const regInfo = resolveRegister(text, { filename: label, flagRegister, config: fileCfg });
|
|
3733
|
-
const packRes = resolveTextPackAndSource(text, label, mod, flags.pack || "auto", fileCfg, packs);
|
|
3734
|
-
const strategy = getScenarioStrategy({ packId: packRes.effectivePack, register: regInfo.register });
|
|
3735
|
-
const auditRes = auditText(text, { filename: label, modality: mod, pack: packRes.pack, config: fileCfg, register: regInfo.register });
|
|
3736
|
-
const ruleFindings = auditRes.findings;
|
|
3737
|
-
const patRes = auditPatterns(text, { filename: label, modality: mod, banks: loadPatternBanks(), config: fileCfg });
|
|
3738
|
-
const patternFindings = patRes.findings;
|
|
3739
|
-
let findings = mergePatternBankFindings(ruleFindings, patternFindings);
|
|
3740
|
-
const profile = PROSE_ML_MODALITIES.has(mod) ? analyzeTextProfile(text, { modality: mod, config: fileCfg }) : null;
|
|
3741
|
-
let mlFindings = [];
|
|
3742
|
-
if (PROSE_ML_MODALITIES.has(mod)) {
|
|
3743
|
-
const mlSrc = mod === "html" || mod === "svg" ? buildZones(text, mod, fileCfg).prose : text;
|
|
3744
|
-
mlFindings = buildPocketMlFindings(mlSrc, label, findings, null, { profile, modality: mod }).findings;
|
|
3745
|
-
findings = [...findings, ...mlFindings];
|
|
3746
|
-
}
|
|
3747
|
-
const crossCheck = buildCrossCheckSummary({
|
|
3748
|
-
ruleFindings,
|
|
3749
|
-
patternFindings,
|
|
3750
|
-
profile,
|
|
3751
|
-
mlFindings,
|
|
3752
|
-
mergedFindings: findings,
|
|
3753
|
-
modality: mod,
|
|
3754
|
-
});
|
|
3755
|
-
|
|
3756
|
-
const detIssues = findingsToReviewIssues(findings, lang);
|
|
3757
|
-
let issues = [...detIssues];
|
|
3758
|
-
let mode = "offline-deterministic";
|
|
3759
|
-
let summary =
|
|
3760
|
-
issues.length === 0
|
|
3761
|
-
? lang === "zh" ? "未发现确定性 AI 味或硬伤问题。" : "No deterministic AI-slop issues detected."
|
|
3762
|
-
: lang === "zh" ? `发现 ${issues.length} 处多信号审校建议(覆盖 ${crossCheck.signalsPresent.join("+") || "rules"},改后可用 dislop verify 校验)。` : `Found ${issues.length} multi-signal review item(s) across ${crossCheck.signalsPresent.join("+") || "rules"}.`;
|
|
3763
|
-
|
|
3764
|
-
const endpoint = flags.offline
|
|
3765
|
-
? ""
|
|
3766
|
-
: String(flags.endpoint || process.env.DISLOP_REVIEW_ENDPOINT || process.env.OPENAI_BASE_URL || "").trim();
|
|
3767
|
-
const keyEnvName = flags["api-key-env"]
|
|
3768
|
-
? String(flags["api-key-env"])
|
|
3769
|
-
: process.env.DISLOP_REVIEW_API_KEY
|
|
3770
|
-
? "DISLOP_REVIEW_API_KEY"
|
|
3771
|
-
: process.env.OPENAI_API_KEY
|
|
3772
|
-
? "OPENAI_API_KEY"
|
|
3773
|
-
: "";
|
|
3774
|
-
const apiKey = keyEnvName ? String(process.env[keyEnvName] || "") : "";
|
|
3775
|
-
|
|
3776
|
-
if (!flags.offline && endpoint && apiKey) {
|
|
3777
|
-
let u;
|
|
3778
|
-
try {
|
|
3779
|
-
u = new URL(endpoint);
|
|
3780
|
-
} catch {
|
|
3781
|
-
console.error(`dislop review: invalid endpoint URL '${endpoint}'`);
|
|
3782
|
-
process.exit(2);
|
|
3783
|
-
}
|
|
3784
|
-
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
3785
|
-
console.error(`dislop review: endpoint must use http or https scheme`);
|
|
3786
|
-
process.exit(2);
|
|
3787
|
-
}
|
|
3788
|
-
if (process.env.DISLOP_TEST_MODE === "1" && !["127.0.0.1", "localhost", "::1", "[::1]"].includes(u.hostname)) {
|
|
3789
|
-
console.error("dislop review: live BYOK requests are blocked when DISLOP_TEST_MODE=1");
|
|
3790
|
-
process.exit(2);
|
|
3791
|
-
}
|
|
3792
|
-
const chatUrl = endpoint.endsWith("/chat/completions") ? endpoint : `${endpoint.replace(/\/+$/, "")}/chat/completions`;
|
|
3793
|
-
const modelId = String(flags.model || process.env.DISLOP_REVIEW_MODEL || "gpt-4o-mini");
|
|
3794
|
-
const stratTag = lang === "zh" ? "zh" : "en";
|
|
3795
|
-
const sysPrompt =
|
|
3796
|
-
lang === "zh"
|
|
3797
|
-
? `你是 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) 绝不改丢数字或范围限定词(预计/仅在/除非/待确认)。`
|
|
3798
|
-
: `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.`;
|
|
3799
|
-
const rubricDigest = buildRubricPromptDigest(rubric, lang);
|
|
3800
|
-
const userPrompt = [
|
|
3801
|
-
`Modality: ${mod} | Pack: ${packRes.effectivePack} | Register: ${regInfo.register} | Scenario: ${strategy.id}`,
|
|
3802
|
-
`Scenario Strategy (${strategy.label[stratTag]}): cut=[${strategy.cut[stratTag]}] protect=[${strategy.protect[stratTag]}] avoid=[${strategy.avoid[stratTag]}]`,
|
|
3803
|
-
...(rubricDigest ? [`5-Layer AI-Tic Rubric:\n${rubricDigest}`] : []),
|
|
3804
|
-
`Local Cross-Check Signals: ${JSON.stringify(crossCheck)}`,
|
|
3805
|
-
...(voiceInfo.found && voiceInfo.card?.profile ? [`Author style card (${voiceInfo.scope}): ${JSON.stringify(voiceInfo.card.profile)}`] : []),
|
|
3806
|
-
`Deterministic findings: ${JSON.stringify(detIssues.slice(0, 12).map((x) => ({ ruleId: x.ruleId, ticLayer: x.ticLayer, quote: x.quote, fixStrategy: x.fixStrategy })))}`,
|
|
3807
|
-
`Draft:\n${text}`,
|
|
3808
|
-
].join("\n\n");
|
|
3809
|
-
try {
|
|
3810
|
-
const resp = await fetch(chatUrl, {
|
|
3811
|
-
method: "POST",
|
|
3812
|
-
headers: {
|
|
3813
|
-
"Content-Type": "application/json",
|
|
3814
|
-
Authorization: `Bearer ${apiKey}`,
|
|
3815
|
-
},
|
|
3816
|
-
body: JSON.stringify({
|
|
3817
|
-
model: modelId,
|
|
3818
|
-
temperature: 0.2,
|
|
3819
|
-
messages: [
|
|
3820
|
-
{ role: "system", content: sysPrompt },
|
|
3821
|
-
{ role: "user", content: userPrompt },
|
|
3822
|
-
],
|
|
3823
|
-
}),
|
|
3824
|
-
signal: AbortSignal.timeout(30000),
|
|
3825
|
-
});
|
|
3826
|
-
if (!resp.ok) {
|
|
3827
|
-
throw new Error(`HTTP ${resp.status}`);
|
|
3828
|
-
}
|
|
3829
|
-
const data = await resp.json();
|
|
3830
|
-
const rawContent = String(data?.choices?.[0]?.message?.content || "").trim();
|
|
3831
|
-
const jsonBody = rawContent.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
|
|
3832
|
-
const parsed = JSON.parse(jsonBody);
|
|
3833
|
-
const lineStarts = [0];
|
|
3834
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
3835
|
-
if (text[i] === "\n") lineStarts.push(i + 1);
|
|
3836
|
-
}
|
|
3837
|
-
const detQuotes = new Set(detIssues.map((d) => d.quote).filter(Boolean));
|
|
3838
|
-
const llmGrounded = groundByokLlmIssues(parsed?.issues, text, lineStarts).filter((i) => !detQuotes.has(i.quote));
|
|
3839
|
-
issues = [...detIssues, ...llmGrounded];
|
|
3840
|
-
mode = "byok-llm";
|
|
3841
|
-
if (typeof parsed?.summary === "string" && parsed.summary.trim()) {
|
|
3842
|
-
summary = parsed.summary.trim();
|
|
3843
|
-
}
|
|
3844
|
-
} catch (err) {
|
|
3845
|
-
console.error(`dislop review: endpoint call failed (${err.message})`);
|
|
3846
|
-
process.exit(2);
|
|
3847
|
-
}
|
|
3848
|
-
}
|
|
3849
|
-
|
|
3850
|
-
const out = {
|
|
3851
|
-
schema: "dislop.review/1",
|
|
3852
|
-
mode,
|
|
3853
|
-
file: label,
|
|
3854
|
-
modality: mod,
|
|
3855
|
-
effectivePack: packRes.effectivePack,
|
|
3856
|
-
packSource: packRes.packSource,
|
|
3857
|
-
register: regInfo.register,
|
|
3858
|
-
scenarioStrategy: strategy.id,
|
|
3859
|
-
crossCheck,
|
|
3860
|
-
rubricLayers: (rubric.layers || []).map((l) => l.id),
|
|
3861
|
-
voiceCard: { found: voiceInfo.found, scope: voiceInfo.scope },
|
|
3862
|
-
...(profile ? { profile } : {}),
|
|
3863
|
-
summary,
|
|
3864
|
-
issues,
|
|
3865
|
-
};
|
|
3866
|
-
prepareEdits(out, text, target);
|
|
3867
|
-
if (flags["interactive-apply"]) return applyReview(out, target, flags, true);
|
|
3868
|
-
|
|
3869
|
-
if (format === "json") {
|
|
3870
|
-
console.log(JSON.stringify(out, null, 2));
|
|
3871
|
-
return;
|
|
3872
|
-
}
|
|
3873
|
-
const isZh = lang === "zh";
|
|
3874
|
-
const stratLabelsZh = { delete: "删掉", "need-source": "补出处", "unwrap-layout": "去套壳", rephrase: "改写" };
|
|
3875
|
-
const actLabelsZh = { edit: "修改", rewrite: "改写", ask: "核实" };
|
|
3876
|
-
const modeLabelZh = mode === "byok-llm" ? "本地+BYOK联合审校" : "四路离线核对";
|
|
3877
|
-
const vcNote = voiceInfo.found ? (isZh ? ` · 个人文风:${voiceInfo.scope}` : ` · voice:${voiceInfo.scope}`) : "";
|
|
3878
|
-
const layerStr = Object.entries(crossCheck.layerCounts)
|
|
3879
|
-
.map(([k, v]) => `${k}×${v}`)
|
|
3880
|
-
.join(", ") || (isZh ? "无明确命中" : "none");
|
|
3881
|
-
const sigStr = crossCheck.signalsPresent.join("+") || "rules";
|
|
3882
|
-
console.log(`dislop review (${label} · ${isZh ? modeLabelZh : mode} · ${packRes.effectivePack}${vcNote})`);
|
|
3883
|
-
console.log(isZh ? ` 摘要 : ${summary}` : ` summary : ${summary}`);
|
|
3884
|
-
console.log(isZh ? ` 信号分布: ${sigStr} | 层级: ${layerStr}` : ` signals : ${sigStr} | layers: ${layerStr}`);
|
|
3885
|
-
for (const iss of issues) {
|
|
3886
|
-
const tag = isZh ? stratLabelsZh[iss.fixStrategy] || iss.fixStrategy : iss.fixStrategy;
|
|
3887
|
-
const act = isZh ? actLabelsZh[iss.action] || iss.action : iss.action;
|
|
3888
|
-
const layerTag = iss.ticLayer ? ` · ${iss.ticLayer}` : "";
|
|
3889
|
-
console.log(` [${String(iss.severity).toUpperCase()}] ${iss.line}:${iss.col} ${act} (${tag}${layerTag}) "${iss.quote}"`);
|
|
3890
|
-
console.log(isZh ? ` 原因: ${iss.why}` : ` why: ${iss.why}`);
|
|
3891
|
-
if (iss.action === "edit") {
|
|
3892
|
-
console.log(isZh ? ` 替换: ${JSON.stringify(iss.replacement)}` : ` rep: ${JSON.stringify(iss.replacement)}`);
|
|
3893
|
-
} else if (iss.action === "ask") {
|
|
3894
|
-
console.log(isZh ? ` 追问: ${iss.question}` : ` ask: ${iss.question}`);
|
|
3895
|
-
} else if (iss.instruction && iss.instruction !== iss.why) {
|
|
3896
|
-
console.log(isZh ? ` 改法: ${iss.instruction}` : ` how: ${iss.instruction}`);
|
|
3897
|
-
}
|
|
3898
|
-
}
|
|
3899
|
-
if (mode === "offline-deterministic" && crossCheck.llmRecommended) {
|
|
3900
|
-
console.log(
|
|
3901
|
-
isZh
|
|
3902
|
-
? " 深查提示: 思维“端水”(cognitive-framing)与说教角度(rhetorical-stance)可配 --endpoint 或云端 dislop_review 联合复核。"
|
|
3903
|
-
: " tip: Pass --endpoint (or use Cloud dislop_review) for LLM semantic cross-check on cognitive-framing and rhetorical-stance."
|
|
3904
|
-
);
|
|
3905
|
-
}
|
|
3906
|
-
}
|
|
3907
|
-
|
|
3908
|
-
async function runProviderReview(flags, positional, packs) {
|
|
3909
|
-
if (positional.length > 1) {
|
|
3910
|
-
console.error("dislop review: inspect one file or '-' stdin per invocation.");
|
|
3911
|
-
process.exit(2);
|
|
3912
|
-
}
|
|
3913
|
-
const target = positional[0] || "-";
|
|
3914
|
-
const cwd = process.cwd();
|
|
3915
|
-
const config = loadConfigOrExit(cwd, flags.config || null);
|
|
3916
|
-
const lang = flags.lang || "en";
|
|
3917
|
-
if (!["en", "zh"].includes(lang)) {
|
|
3918
|
-
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
3919
|
-
process.exit(2);
|
|
3920
|
-
}
|
|
3921
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
3922
|
-
if (!["text", "json", "agent"].includes(format)) {
|
|
3923
|
-
console.error(`dislop review: invalid --format '${format}' (expected text, json, or agent)`);
|
|
3924
|
-
process.exit(2);
|
|
3925
|
-
}
|
|
3926
|
-
const failOn = flags["fail-on"] || "warning";
|
|
3927
|
-
if (!SEVERITY_RANK[failOn]) {
|
|
3928
|
-
console.error(`dislop review: invalid --fail-on '${failOn}' (expected error, warning, info, or never)`);
|
|
3929
|
-
process.exit(2);
|
|
3930
|
-
}
|
|
3931
|
-
let timeoutMs = 30000;
|
|
3932
|
-
if (flags.timeout !== undefined) {
|
|
3933
|
-
const rawT = String(flags.timeout).trim();
|
|
3934
|
-
if (!/^\d+$/.test(rawT)) {
|
|
3935
|
-
console.error("dislop review: --timeout must be an integer between 1000 and 120000 ms");
|
|
3936
|
-
process.exit(2);
|
|
3937
|
-
}
|
|
3938
|
-
timeoutMs = Number(rawT);
|
|
3939
|
-
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 120000) {
|
|
3940
|
-
console.error("dislop review: --timeout must be between 1000 and 120000 ms");
|
|
3941
|
-
process.exit(2);
|
|
3942
|
-
}
|
|
3943
|
-
}
|
|
3944
|
-
let maxChunks = 20;
|
|
3945
|
-
if (flags["max-chunks"] !== undefined) {
|
|
3946
|
-
const rawC = String(flags["max-chunks"]).trim();
|
|
3947
|
-
if (!/^\d+$/.test(rawC)) {
|
|
3948
|
-
console.error("dislop review: --max-chunks must be an integer between 1 and 100");
|
|
3949
|
-
process.exit(2);
|
|
3950
|
-
}
|
|
3951
|
-
maxChunks = Number(rawC);
|
|
3952
|
-
if (!Number.isSafeInteger(maxChunks) || maxChunks < 1 || maxChunks > 100) {
|
|
3953
|
-
console.error("dislop review: --max-chunks must be between 1 and 100");
|
|
3954
|
-
process.exit(2);
|
|
3955
|
-
}
|
|
3956
|
-
}
|
|
3957
|
-
|
|
3958
|
-
let rawText = "";
|
|
3959
|
-
let filename = "stdin.md";
|
|
3960
|
-
let modality = "markdown";
|
|
3961
|
-
if (target === "-") {
|
|
3962
|
-
rawText = readStdinTextChecked("review");
|
|
3963
|
-
filename = detectStdinFilename(rawText, flags["stdin-filename"]);
|
|
3964
|
-
modality = detectModality(filename) || "markdown";
|
|
3965
|
-
if (flags["stdin-filename"] && (modality === "docx" || modality === "pptx" || modality === "pdf")) {
|
|
3966
|
-
console.error(`dislop review: '--stdin-filename' cannot treat stdin as binary '${modality}'; pass the file path directly.`);
|
|
3967
|
-
process.exit(2);
|
|
3968
|
-
}
|
|
3969
|
-
} else {
|
|
3970
|
-
const absPath = path.resolve(cwd, target);
|
|
3971
|
-
if (!fs.existsSync(absPath) || !fs.statSync(absPath).isFile()) {
|
|
3972
|
-
console.error(`dislop review: file not found: ${target}`);
|
|
3973
|
-
process.exit(2);
|
|
3974
|
-
}
|
|
3975
|
-
const rel = path.relative(cwd, absPath);
|
|
3976
|
-
filename =
|
|
3977
|
-
rel && !rel.startsWith("..") && !path.isAbsolute(rel)
|
|
3978
|
-
? rel.split(path.sep).join("/")
|
|
3979
|
-
: path.basename(absPath);
|
|
3980
|
-
modality = detectModality(absPath);
|
|
3981
|
-
if (!modality) {
|
|
3982
|
-
console.error(`dislop review: unsupported file type '${path.extname(absPath) || "(none)"}'`);
|
|
3983
|
-
process.exit(2);
|
|
3984
|
-
}
|
|
3985
|
-
const buf = fs.readFileSync(absPath);
|
|
3986
|
-
if (modality === "docx" || modality === "pptx") {
|
|
3987
|
-
try {
|
|
3988
|
-
const entries = readZipXmlEntries(buf);
|
|
3989
|
-
rawText = extractOoxmlReviewText(entries, modality, {
|
|
3990
|
-
includeNotes: Boolean(flags["include-notes"]),
|
|
3991
|
-
includeHidden: Boolean(flags["include-hidden"]),
|
|
3992
|
-
});
|
|
3993
|
-
} catch (err) {
|
|
3994
|
-
console.error(`dislop review: ${err.message}`);
|
|
3995
|
-
process.exit(2);
|
|
3996
|
-
}
|
|
3997
|
-
} else {
|
|
3998
|
-
try {
|
|
3999
|
-
rawText = decodeUtf8Strict(buf);
|
|
4000
|
-
} catch {
|
|
4001
|
-
console.error(`dislop review: '${target}' is not valid UTF-8 text`);
|
|
4002
|
-
process.exit(2);
|
|
4003
|
-
}
|
|
4004
|
-
}
|
|
4005
|
-
}
|
|
4006
|
-
filename = String(filename).replace(/[\r\n]+/g, " ").trim() || "draft.md";
|
|
4007
|
-
|
|
4008
|
-
if (!rawText.trim()) {
|
|
4009
|
-
console.error("dislop review: extracted draft text is empty");
|
|
4010
|
-
process.exit(2);
|
|
4011
|
-
}
|
|
4012
|
-
|
|
4013
|
-
const flagRegister = flags.register !== undefined ? String(flags.register).trim().toLowerCase() : null;
|
|
4014
|
-
let regInfo;
|
|
4015
|
-
try {
|
|
4016
|
-
regInfo = resolveRegister(rawText, {
|
|
4017
|
-
filename,
|
|
4018
|
-
flagRegister,
|
|
4019
|
-
config,
|
|
4020
|
-
});
|
|
4021
|
-
} catch (err) {
|
|
4022
|
-
console.error(`dislop review: ${err.message}`);
|
|
4023
|
-
process.exit(2);
|
|
4024
|
-
}
|
|
4025
|
-
|
|
4026
|
-
const packFlag = flags.pack === "auto" && (modality === "markdown" || modality === "text")
|
|
4027
|
-
? predictPackWithPocketRouter(rawText).recommendedPack
|
|
4028
|
-
: flags.pack === "auto"
|
|
4029
|
-
? null
|
|
4030
|
-
: flags.pack || null;
|
|
4031
|
-
const packId = pickPackForFile(filename, modality, packFlag, config);
|
|
4032
|
-
if (!packs[packId]) {
|
|
4033
|
-
console.error(`dislop review: unknown pack '${packId}'`);
|
|
4034
|
-
process.exit(2);
|
|
4035
|
-
}
|
|
4036
|
-
|
|
4037
|
-
let prov;
|
|
4038
|
-
const isDryRun = Boolean(flags["dry-run"]);
|
|
4039
|
-
const isPrintPrompt = Boolean(flags["print-prompt"]);
|
|
4040
|
-
try {
|
|
4041
|
-
prov = resolveProviderConfig({
|
|
4042
|
-
provider: flags.provider || process.env.DISLOP_REVIEW_PROVIDER || "openai",
|
|
4043
|
-
model: flags.model || null,
|
|
4044
|
-
baseUrl: flags["base-url"] || null,
|
|
4045
|
-
allowMissingKey: isDryRun || isPrintPrompt,
|
|
4046
|
-
env: process.env,
|
|
4047
|
-
});
|
|
4048
|
-
} catch (err) {
|
|
4049
|
-
console.error(`dislop review: ${err.message}`);
|
|
4050
|
-
process.exit(2);
|
|
4051
|
-
}
|
|
4052
|
-
|
|
4053
|
-
let chunks;
|
|
4054
|
-
try {
|
|
4055
|
-
chunks = chunkTextByParagraphs(rawText, 10000, { maxChunks });
|
|
4056
|
-
} catch (err) {
|
|
4057
|
-
console.error(`dislop review: ${err.message}`);
|
|
4058
|
-
process.exit(2);
|
|
4059
|
-
}
|
|
4060
|
-
|
|
4061
|
-
const firstPrompt = buildReviewPrompt({
|
|
4062
|
-
chunkText: chunks[0].text,
|
|
4063
|
-
filename,
|
|
4064
|
-
modality,
|
|
4065
|
-
packId,
|
|
4066
|
-
register: regInfo.register,
|
|
4067
|
-
lang,
|
|
4068
|
-
});
|
|
4069
|
-
const totalBytes = Buffer.byteLength(rawText, "utf8");
|
|
4070
|
-
const consentMode = prov.isLocal
|
|
4071
|
-
? "local-loopback"
|
|
4072
|
-
: flags.yes
|
|
4073
|
-
? "--yes"
|
|
4074
|
-
: process.env.DISLOP_ALLOW_REMOTE === "1"
|
|
4075
|
-
? "DISLOP_ALLOW_REMOTE=1"
|
|
4076
|
-
: "required";
|
|
4077
|
-
|
|
4078
|
-
if (isPrintPrompt) {
|
|
4079
|
-
if (format === "json") {
|
|
4080
|
-
console.log(
|
|
4081
|
-
JSON.stringify(
|
|
4082
|
-
{
|
|
4083
|
-
schema: "dislop.review-prompt/1",
|
|
4084
|
-
provider: prov.provider,
|
|
4085
|
-
host: prov.host,
|
|
4086
|
-
model: prov.model,
|
|
4087
|
-
chunks: chunks.length,
|
|
4088
|
-
bytes: totalBytes,
|
|
4089
|
-
delimiter: firstPrompt.delimiter,
|
|
4090
|
-
systemPrompt: firstPrompt.systemPrompt,
|
|
4091
|
-
userPrompt: firstPrompt.userPrompt,
|
|
4092
|
-
},
|
|
4093
|
-
null,
|
|
4094
|
-
2
|
|
4095
|
-
)
|
|
4096
|
-
);
|
|
4097
|
-
} else {
|
|
4098
|
-
console.log(`=== SYSTEM PROMPT ===\n${firstPrompt.systemPrompt}\n\n=== USER PROMPT (chunk 1/${chunks.length}) ===\n${firstPrompt.userPrompt}`);
|
|
4099
|
-
}
|
|
4100
|
-
return;
|
|
4101
|
-
}
|
|
4102
|
-
|
|
4103
|
-
if (isDryRun) {
|
|
4104
|
-
const dryPayload = {
|
|
4105
|
-
schema: "dislop.review-dry-run/1",
|
|
4106
|
-
provider: prov.provider,
|
|
4107
|
-
host: prov.host,
|
|
4108
|
-
endpointUrl: prov.safeUrl,
|
|
4109
|
-
model: prov.model,
|
|
4110
|
-
consent: consentMode,
|
|
4111
|
-
keyPresent: Boolean(prov.apiKey),
|
|
4112
|
-
keySource: prov.keySource,
|
|
4113
|
-
headers: {
|
|
4114
|
-
"content-type": "application/json",
|
|
4115
|
-
...(prov.apiKey ? { authorization: "Bearer <REDACTED>" } : {}),
|
|
4116
|
-
},
|
|
4117
|
-
file: filename,
|
|
4118
|
-
modality,
|
|
4119
|
-
pack: packId,
|
|
4120
|
-
context: regInfo,
|
|
4121
|
-
chunks: chunks.length,
|
|
4122
|
-
bytes: totalBytes,
|
|
4123
|
-
requestBody: {
|
|
4124
|
-
model: prov.model,
|
|
4125
|
-
temperature: 0,
|
|
4126
|
-
messages: [
|
|
4127
|
-
{ role: "system", content: firstPrompt.systemPrompt },
|
|
4128
|
-
{ role: "user", content: firstPrompt.userPrompt },
|
|
4129
|
-
],
|
|
4130
|
-
},
|
|
4131
|
-
};
|
|
4132
|
-
if (format === "json") {
|
|
4133
|
-
console.log(JSON.stringify(dryPayload, null, 2));
|
|
4134
|
-
} else if (lang === "zh") {
|
|
4135
|
-
console.log(`dislop review 演练(0 次网络请求)`);
|
|
4136
|
-
console.log(` 目标接口 : ${prov.safeUrl} (provider=${prov.provider}, model=${prov.model}, consent=${consentMode})`);
|
|
4137
|
-
console.log(` 鉴权来源 : ${prov.apiKey ? `环境变量 ${prov.keySource}(已脱敏)` : "未设置 / 本地免密钥"}`);
|
|
4138
|
-
console.log(` 待审文稿 : ${filename}(${totalBytes} 字节,${chunks.length} 段,语域=${regInfo.register})`);
|
|
4139
|
-
console.log(` 分隔标记 : ${firstPrompt.delimiter}`);
|
|
4140
|
-
} else {
|
|
4141
|
-
console.log(`dislop review dry-run: 0 network calls made`);
|
|
4142
|
-
console.log(` destination : ${prov.safeUrl} (provider=${prov.provider}, model=${prov.model}, consent=${consentMode})`);
|
|
4143
|
-
console.log(` auth : ${prov.apiKey ? `env ${prov.keySource} (redacted)` : "none/unset"}`);
|
|
4144
|
-
console.log(` draft : ${filename} (${totalBytes} bytes, ${chunks.length} chunk(s), register=${regInfo.register})`);
|
|
4145
|
-
console.log(` delimiter : ${firstPrompt.delimiter}`);
|
|
4146
|
-
}
|
|
4147
|
-
return;
|
|
4148
|
-
}
|
|
4149
|
-
|
|
4150
|
-
if (!prov.isLocal && Array.isArray(config?.forbid) && config.forbid.length > 0) {
|
|
4151
|
-
const hitLocs = [];
|
|
4152
|
-
for (const pat of config.forbid) {
|
|
4153
|
-
let re;
|
|
4154
|
-
try {
|
|
4155
|
-
re = new RegExp(pat, "gimu");
|
|
4156
|
-
} catch (err) {
|
|
4157
|
-
console.error(`dislop review: invalid .dislop.local.json forbid regex: ${err.message}`);
|
|
4158
|
-
process.exit(2);
|
|
4159
|
-
}
|
|
4160
|
-
if (re.test(filename)) {
|
|
4161
|
-
hitLocs.push("filename");
|
|
4162
|
-
}
|
|
4163
|
-
re.lastIndex = 0;
|
|
4164
|
-
let m;
|
|
4165
|
-
while ((m = re.exec(rawText)) !== null) {
|
|
4166
|
-
const lineNum = rawText.slice(0, m.index).split("\n").length;
|
|
4167
|
-
hitLocs.push(String(lineNum));
|
|
4168
|
-
if (hitLocs.length >= 20) break;
|
|
4169
|
-
if (m[0].length === 0) {
|
|
4170
|
-
if (re.lastIndex >= rawText.length) break;
|
|
4171
|
-
const cp = rawText.codePointAt(m.index);
|
|
4172
|
-
re.lastIndex = m.index + (cp !== undefined && cp > 0xffff ? 2 : 1);
|
|
4173
|
-
}
|
|
4174
|
-
}
|
|
4175
|
-
}
|
|
4176
|
-
if (hitLocs.length > 0) {
|
|
4177
|
-
const uniqueLocs = Array.from(new Set(hitLocs)).slice(0, 5).join(", ");
|
|
4178
|
-
console.error(
|
|
4179
|
-
`dislop review: refusing remote upload — matched ${hitLocs.length} local '.dislop.local.json' forbid policy hit(s) (${uniqueLocs}).`
|
|
4180
|
-
);
|
|
4181
|
-
process.exit(2);
|
|
4182
|
-
}
|
|
4183
|
-
}
|
|
4184
|
-
|
|
4185
|
-
if (prov.isLocal) {
|
|
4186
|
-
try {
|
|
4187
|
-
await assertLoopbackEndpoint(prov.hostname);
|
|
4188
|
-
} catch (err) {
|
|
4189
|
-
console.error(`dislop review: ${scrubSecrets(err.message, prov.apiKey ? [prov.apiKey] : [])}`);
|
|
4190
|
-
process.exit(2);
|
|
4191
|
-
}
|
|
4192
|
-
} else if (!flags.yes && process.env.DISLOP_ALLOW_REMOTE !== "1") {
|
|
4193
|
-
console.error(
|
|
4194
|
-
`dislop review: refusing remote upload without explicit confirmation (--yes or DISLOP_ALLOW_REMOTE=1).\n` +
|
|
4195
|
-
` target: host=${prov.host} provider=${prov.provider} model=${prov.model} file=${filename} bytes=${totalBytes} chunks=${chunks.length}`
|
|
4196
|
-
);
|
|
4197
|
-
process.exit(2);
|
|
4198
|
-
}
|
|
4199
|
-
|
|
4200
|
-
console.error(
|
|
4201
|
-
`dislop review: sending to host=${prov.host} provider=${prov.provider} model=${prov.model} file=${filename} bytes=${totalBytes} chunks=${chunks.length} register=${regInfo.register}`
|
|
4202
|
-
);
|
|
4203
|
-
|
|
4204
|
-
const allFindings = [];
|
|
4205
|
-
const seenFingerprints = new Set();
|
|
4206
|
-
const rejected = { ungroundedQuote: 0, inventedFact: 0, malformed: 0 };
|
|
4207
|
-
const summaries = [];
|
|
4208
|
-
const levels = [];
|
|
4209
|
-
let promptTokens = 0;
|
|
4210
|
-
let completionTokens = 0;
|
|
4211
|
-
let totalTokens = 0;
|
|
4212
|
-
let hasUsage = false;
|
|
4213
|
-
const redactList = prov.apiKey ? [prov.apiKey] : [];
|
|
4214
|
-
|
|
4215
|
-
for (const ch of chunks) {
|
|
4216
|
-
const prompt = ch.index === 0
|
|
4217
|
-
? firstPrompt
|
|
4218
|
-
: buildReviewPrompt({
|
|
4219
|
-
chunkText: ch.text,
|
|
4220
|
-
filename,
|
|
4221
|
-
modality,
|
|
4222
|
-
packId,
|
|
4223
|
-
register: regInfo.register,
|
|
4224
|
-
lang,
|
|
4225
|
-
});
|
|
4226
|
-
try {
|
|
4227
|
-
const apiRes = await runReviewRequest({
|
|
4228
|
-
endpointUrl: prov.endpointUrl,
|
|
4229
|
-
isLocal: prov.isLocal,
|
|
4230
|
-
hostname: prov.hostname,
|
|
4231
|
-
model: prov.model,
|
|
4232
|
-
apiKey: prov.apiKey,
|
|
4233
|
-
systemPrompt: prompt.systemPrompt,
|
|
4234
|
-
userPrompt: prompt.userPrompt,
|
|
4235
|
-
timeoutMs,
|
|
4236
|
-
});
|
|
4237
|
-
if (apiRes.usage && typeof apiRes.usage === "object" && !Array.isArray(apiRes.usage)) {
|
|
4238
|
-
try {
|
|
4239
|
-
const MAX_TOK = 1_000_000_000;
|
|
4240
|
-
const safeCount = (v) => {
|
|
4241
|
-
if (typeof v === "number") {
|
|
4242
|
-
return Number.isSafeInteger(v) && v >= 0 && v <= MAX_TOK ? v : 0;
|
|
4243
|
-
}
|
|
4244
|
-
if (typeof v === "string") {
|
|
4245
|
-
const s = v.trim();
|
|
4246
|
-
if (/^\d{1,10}$/.test(s)) {
|
|
4247
|
-
const n = Number(s);
|
|
4248
|
-
return Number.isSafeInteger(n) && n <= MAX_TOK ? n : 0;
|
|
4249
|
-
}
|
|
4250
|
-
}
|
|
4251
|
-
return 0;
|
|
4252
|
-
};
|
|
4253
|
-
const pt = safeCount(apiRes.usage.prompt_tokens);
|
|
4254
|
-
const ct = safeCount(apiRes.usage.completion_tokens);
|
|
4255
|
-
const tt = safeCount(apiRes.usage.total_tokens);
|
|
4256
|
-
hasUsage = true;
|
|
4257
|
-
promptTokens += pt;
|
|
4258
|
-
completionTokens += ct;
|
|
4259
|
-
totalTokens += tt;
|
|
4260
|
-
} catch {}
|
|
4261
|
-
}
|
|
4262
|
-
const norm = validateAndNormalizeReviewResponse({
|
|
4263
|
-
rawContent: apiRes.content,
|
|
4264
|
-
chunkText: ch.text,
|
|
4265
|
-
fullText: rawText,
|
|
4266
|
-
chunkStartOffset: ch.startOffset,
|
|
4267
|
-
filename,
|
|
4268
|
-
modality,
|
|
4269
|
-
lang,
|
|
4270
|
-
redactSecrets: redactList,
|
|
4271
|
-
});
|
|
4272
|
-
for (const f of norm.findings) {
|
|
4273
|
-
if (!seenFingerprints.has(f.fingerprint)) {
|
|
4274
|
-
seenFingerprints.add(f.fingerprint);
|
|
4275
|
-
allFindings.push(f);
|
|
4276
|
-
}
|
|
4277
|
-
}
|
|
4278
|
-
rejected.ungroundedQuote += norm.rejected.ungroundedQuote;
|
|
4279
|
-
rejected.inventedFact += norm.rejected.inventedFact;
|
|
4280
|
-
rejected.malformed += norm.rejected.malformed;
|
|
4281
|
-
if (norm.summary) summaries.push(norm.summary);
|
|
4282
|
-
levels.push(norm.aiFlavorLevel);
|
|
4283
|
-
} catch (err) {
|
|
4284
|
-
console.error(`dislop review: chunk ${ch.index + 1}/${chunks.length} failed — ${scrubSecrets(err.message, redactList)}`);
|
|
4285
|
-
process.exit(2);
|
|
4286
|
-
}
|
|
4287
|
-
}
|
|
4288
|
-
|
|
4289
|
-
const overallLevel = levels.includes("high") ? "high" : levels.includes("medium") ? "medium" : "low";
|
|
4290
|
-
const levelLabel = lang === "zh" ? ({ high: "高", medium: "中", low: "低" }[overallLevel] || overallLevel) : overallLevel;
|
|
4291
|
-
const summaryText = summaries.join(" ").trim();
|
|
4292
|
-
const usageSummary = hasUsage
|
|
4293
|
-
? { promptTokens, completionTokens, totalTokens }
|
|
4294
|
-
: null;
|
|
4295
|
-
const report = {
|
|
4296
|
-
schema: "dislop.review/1",
|
|
4297
|
-
version: ENGINE_VERSION,
|
|
4298
|
-
provider: prov.provider,
|
|
4299
|
-
host: prov.host,
|
|
4300
|
-
model: prov.model,
|
|
4301
|
-
file: filename,
|
|
4302
|
-
pack: packId,
|
|
4303
|
-
lang,
|
|
4304
|
-
chunks: chunks.length,
|
|
4305
|
-
bytes: totalBytes,
|
|
4306
|
-
aiFlavorLevel: overallLevel,
|
|
4307
|
-
summary: summaryText,
|
|
4308
|
-
context: { register: regInfo.register, registerSource: regInfo.registerSource },
|
|
4309
|
-
checkedCount: 1,
|
|
4310
|
-
skipped: [],
|
|
4311
|
-
findings: allFindings,
|
|
4312
|
-
unusedSuppressions: [],
|
|
4313
|
-
rejected,
|
|
4314
|
-
usage: usageSummary,
|
|
4315
|
-
};
|
|
4316
|
-
prepareEdits(report, rawText, target);
|
|
4317
|
-
if (flags["interactive-apply"]) return applyReview(report, target, flags, true);
|
|
4318
|
-
|
|
4319
|
-
if (format === "json") {
|
|
4320
|
-
console.log(JSON.stringify(report, null, 2));
|
|
4321
|
-
} else {
|
|
4322
|
-
const out = formatReport(report, format, lang, { failOn });
|
|
4323
|
-
console.log(out);
|
|
4324
|
-
if (format === "text" && summaryText) {
|
|
4325
|
-
console.log(lang === "zh" ? ` [综述 · ${levelLabel}] ${summaryText}` : ` [summary · ${overallLevel}] ${summaryText}`);
|
|
4326
|
-
}
|
|
4327
|
-
const rejTotal = rejected.ungroundedQuote + rejected.inventedFact + rejected.malformed;
|
|
4328
|
-
if (format === "text" && rejTotal > 0) {
|
|
4329
|
-
console.log(
|
|
4330
|
-
lang === "zh"
|
|
4331
|
-
? ` [校验过滤] 已丢弃 ${rejTotal} 条未通过核验的建议(无原文引用=${rejected.ungroundedQuote},编造事实=${rejected.inventedFact},格式异常=${rejected.malformed})`
|
|
4332
|
-
: ` [guard] filtered ${rejTotal} unverified suggestion(s) (ungrounded=${rejected.ungroundedQuote}, inventedFact=${rejected.inventedFact}, malformed=${rejected.malformed})`
|
|
4333
|
-
);
|
|
4334
|
-
}
|
|
4335
|
-
}
|
|
4336
|
-
const triggered = allFindings.some((f) => (SEVERITY_RANK[f.severity] || 1) >= SEVERITY_RANK[failOn]);
|
|
4337
|
-
process.exitCode = triggered ? 1 : 0;
|
|
4338
|
-
}
|
|
4339
|
-
|
|
4340
|
-
async function runReview(args, packs) {
|
|
4341
|
-
for (const tok of args) {
|
|
4342
|
-
if (tok === "--api-key" || tok.startsWith("--api-key=") || tok === "--token" || tok.startsWith("--token=")) {
|
|
4343
|
-
console.error(
|
|
4344
|
-
"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."
|
|
4345
|
-
);
|
|
4346
|
-
process.exit(2);
|
|
4347
|
-
}
|
|
4348
|
-
}
|
|
4349
|
-
const { flags, positional } = parseFlags(args, "review");
|
|
4350
|
-
if (flags.help) {
|
|
4351
|
-
printSubcommandHelp("review");
|
|
4352
|
-
return;
|
|
4353
|
-
}
|
|
4354
|
-
if (flags["interactive-apply"]) {
|
|
4355
|
-
requirePicker(positional[0] || "-", positional.length === 1 && !flags.json && (!flags.format || flags.format === "text") &&
|
|
4356
|
-
!flags["dry-run"] && !flags["print-prompt"]);
|
|
4357
|
-
}
|
|
4358
|
-
if (flags.offline || flags.endpoint || flags["api-key-env"]) {
|
|
4359
|
-
return await runRubricReview(flags, positional, packs);
|
|
4360
|
-
}
|
|
4361
|
-
return await runProviderReview(flags, positional, packs);
|
|
4362
|
-
}
|
|
4363
|
-
|
|
4364
|
-
async function runDoctor(args, packs) {
|
|
4365
|
-
const { flags, positional } = parseFlags(args, "doctor");
|
|
4366
|
-
if (flags.help) {
|
|
4367
|
-
printSubcommandHelp("doctor");
|
|
4368
|
-
return;
|
|
4369
|
-
}
|
|
4370
|
-
if (positional.length > 0) {
|
|
4371
|
-
console.error(`dislop doctor: unexpected positional argument '${positional[0]}'.`);
|
|
4372
|
-
process.exit(2);
|
|
4373
|
-
}
|
|
4374
|
-
const lang = flags.lang || "en";
|
|
4375
|
-
if (!["en", "zh"].includes(lang)) {
|
|
4376
|
-
console.error(`dislop: invalid --lang '${lang}' (expected en or zh)`);
|
|
4377
|
-
process.exit(2);
|
|
4378
|
-
}
|
|
4379
|
-
const format = flags.json ? "json" : flags.format || "text";
|
|
4380
|
-
if (!["text", "json"].includes(format)) {
|
|
4381
|
-
console.error(`dislop doctor: invalid --format '${format}' (expected text or json)`);
|
|
4382
|
-
process.exit(2);
|
|
4383
|
-
}
|
|
4384
|
-
const cwd = process.cwd();
|
|
4385
|
-
let rulesCount = 0;
|
|
4386
|
-
for (const p of Object.values(packs)) rulesCount += (p.rules || []).length;
|
|
4387
|
-
const baseStatus = await buildModelStatusReport({
|
|
4388
|
-
packsCount: Object.keys(packs).length,
|
|
4389
|
-
rulesCount,
|
|
4390
|
-
probeLoopback: !flags["no-loopback"],
|
|
4391
|
-
cacheDir: flags["cache-dir"] || null,
|
|
4392
|
-
});
|
|
4393
|
-
|
|
4394
|
-
const skillRel = "skills/dislop/SKILL.md";
|
|
4395
|
-
const workspaceReady = fs.existsSync(path.join(cwd, skillRel));
|
|
4396
|
-
const bundledReady = fs.existsSync(path.join(REPO_ROOT, skillRel));
|
|
4397
|
-
const skillReady = workspaceReady || bundledReady;
|
|
4398
|
-
const byokEnv = inspectByokEnvStatus(process.env);
|
|
4399
|
-
const cfgPathFound = [".dislop.json", "dislop.json", ".disloprc.json", ".dislop.local.json"].some((n) =>
|
|
4400
|
-
fs.existsSync(path.join(cwd, n))
|
|
4401
|
-
);
|
|
4402
|
-
let cfgValid = true;
|
|
4403
|
-
let cfgError = null;
|
|
4404
|
-
try {
|
|
4405
|
-
loadConfig(cwd, null);
|
|
4406
|
-
} catch (err) {
|
|
4407
|
-
cfgValid = false;
|
|
4408
|
-
cfgError = scrubSecrets(err.message);
|
|
4409
|
-
}
|
|
4410
|
-
|
|
4411
|
-
let gitignoreLocalConfig = null;
|
|
4412
|
-
try {
|
|
4413
|
-
const g = spawnSync("git", ["check-ignore", "-q", ".dislop.local.json"], { cwd, encoding: "utf8", timeout: 2000 });
|
|
4414
|
-
if (g.status === 0) gitignoreLocalConfig = true;
|
|
4415
|
-
else if (g.status === 1) gitignoreLocalConfig = false;
|
|
4416
|
-
} catch {}
|
|
4417
|
-
|
|
4418
|
-
const ping = flags.online
|
|
4419
|
-
? await pingEndpointHealth("https://dislop.com/api/health")
|
|
4420
|
-
: { checked: false, ok: null, status: null, error: null };
|
|
4421
|
-
|
|
4422
|
-
const report = {
|
|
4423
|
-
...baseStatus,
|
|
4424
|
-
schema: "dislop.doctor/1",
|
|
4425
|
-
layers: {
|
|
4426
|
-
skill: { ready: skillReady, workspaceReady, bundledReady, path: skillRel },
|
|
4427
|
-
localCli: {
|
|
4428
|
-
ready: true,
|
|
4429
|
-
version: ENGINE_VERSION,
|
|
4430
|
-
packs: Object.keys(packs).length,
|
|
4431
|
-
rules: rulesCount,
|
|
4432
|
-
pocketMlReady: true,
|
|
4433
|
-
localRunnersCount: baseStatus.localRunners.length,
|
|
4434
|
-
},
|
|
4435
|
-
byokReview: byokEnv,
|
|
4436
|
-
officialCloudMcp: {
|
|
4437
|
-
url: "https://dislop.com/mcp",
|
|
4438
|
-
freeCreditsPerMonth: 30,
|
|
4439
|
-
ping,
|
|
4440
|
-
},
|
|
4441
|
-
config: {
|
|
4442
|
-
found: cfgPathFound,
|
|
4443
|
-
valid: cfgValid,
|
|
4444
|
-
error: cfgError,
|
|
4445
|
-
gitignoreLocalConfig,
|
|
4446
|
-
},
|
|
4447
|
-
},
|
|
4448
|
-
};
|
|
4449
|
-
|
|
4450
|
-
if (format === "json") {
|
|
4451
|
-
console.log(JSON.stringify(report, null, 2));
|
|
4452
|
-
if (!cfgValid) process.exitCode = 2;
|
|
4453
|
-
return;
|
|
4454
|
-
}
|
|
4455
|
-
|
|
4456
|
-
const configuredNames = Object.entries(byokEnv.providers)
|
|
4457
|
-
.filter(([, v]) => v.keyPresent)
|
|
4458
|
-
.map(([k, v]) => `${k}(${v.keySource})`);
|
|
4459
|
-
const hw = report.hardware;
|
|
4460
|
-
const rec = report.recommendation;
|
|
4461
|
-
if (lang === "zh") {
|
|
4462
|
-
const skillLabel = workspaceReady ? "已就绪(当前工作区)" : bundledReady ? "已就绪(安装包内置)" : "未找到";
|
|
4463
|
-
const pingLabel = ping.checked
|
|
4464
|
-
? (ping.ok ? `在线连通 HTTP ${ping.status}` : `连通失败:${ping.error || `HTTP ${ping.status}`}`)
|
|
4465
|
-
: (ping.error ? `已拦截(${ping.error})` : "未联网检测,可加 --online");
|
|
4466
|
-
console.log(`dislop doctor v${ENGINE_VERSION}(三层体检 · 默认 0 联网)`);
|
|
4467
|
-
console.log(` 1. 纯文档 Skill : ${skillLabel} (${skillRel})`);
|
|
4468
|
-
console.log(` 2. 本地 CLI 引擎 : 已就绪(${Object.keys(packs).length} 套规则包 / ${rulesCount} 条规则 · 14.6 KB Pocket ML · ${baseStatus.localRunners.length} 个本地推理端)`);
|
|
4469
|
-
console.log(` 硬件与选装推荐 : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB 内存 -> ${rec.tier}${rec.modelId ? ` (${rec.modelId})` : "(内置模型即可)"}`);
|
|
4470
|
-
console.log(` BYOK 深度审校 : ${configuredNames.length > 0 ? `已配置 ${configuredNames.join("、")}` : "未配置密钥环境变量(仅按需 --yes 启用)"}`);
|
|
4471
|
-
console.log(` 3. 官方云端 MCP : https://dislop.com/mcp(免费额度 30 次/月 · ${pingLabel})`);
|
|
4472
|
-
console.log(` 配置与隐私边界 : 配置=${cfgPathFound ? (cfgValid ? "有效" : `异常:${cfgError}`) : "使用默认"} | .dislop.local.json 忽略=${gitignoreLocalConfig === true ? "已忽略" : gitignoreLocalConfig === false ? "未加入 .gitignore" : "非 git 仓库"}`);
|
|
4473
|
-
} else {
|
|
4474
|
-
const skillLabel = workspaceReady ? "ready (workspace)" : bundledReady ? "ready (bundled)" : "not found";
|
|
4475
|
-
const pingLabel = ping.checked
|
|
4476
|
-
? (ping.ok ? `reachable HTTP ${ping.status}` : `unreachable: ${ping.error || `HTTP ${ping.status}`}`)
|
|
4477
|
-
: (ping.error ? `blocked (${ping.error})` : "offline (pass --online to ping)");
|
|
4478
|
-
console.log(`dislop doctor v${ENGINE_VERSION} (3-layer readiness · offline by default)`);
|
|
4479
|
-
console.log(` 1. Pure-doc Skill : ${skillLabel} (${skillRel})`);
|
|
4480
|
-
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))`);
|
|
4481
|
-
console.log(` Hardware fit : ${hw.platform}/${hw.arch} · ${hw.totalMemoryGb} GB RAM -> ${rec.tier}${rec.modelId ? ` (${rec.modelId})` : " (bundled only)"}`);
|
|
4482
|
-
console.log(` BYOK review : ${configuredNames.length > 0 ? `configured: ${configuredNames.join(", ")}` : "no API key env set (explicit opt-in only)"}`);
|
|
4483
|
-
console.log(` 3. Cloud MCP : https://dislop.com/mcp (30 free/mo · ${pingLabel})`);
|
|
4484
|
-
console.log(` Config & hygiene : config=${cfgPathFound ? (cfgValid ? "valid" : `invalid (${cfgError})`) : "defaults"} | .dislop.local.json gitignored=${gitignoreLocalConfig === null ? "n/a" : String(gitignoreLocalConfig)}`);
|
|
4485
|
-
}
|
|
4486
|
-
if (!cfgValid) process.exitCode = 2;
|
|
4487
|
-
}
|
|
4488
|
-
|
|
4489
|
-
function printHelp() {
|
|
4490
|
-
console.log(`dislop v${ENGINE_VERSION} — Cutting AI slop is real productivity. Linter for AI Slop in docs, web UI, and slides
|
|
4491
|
-
|
|
4492
|
-
Usage: dislop <command> [options]
|
|
4493
|
-
|
|
4494
|
-
Check & fix (local, 0 network calls):
|
|
4495
|
-
check [paths... | -] Audit files or stdin [--pack <id|auto>] [--register <id|auto>] [--deep] [-q|--quiet]
|
|
4496
|
-
[--fail-on error|warning|info|never] [--format text|json|agent|sarif|github|md]
|
|
4497
|
-
[--changed [ref] | --staged] [--rule <id,...>] [--lang en|zh]
|
|
4498
|
-
verify <before> <after> Verify edits retain numbers/qualifiers & --keep terms [--git [ref] <file>] [--strict]
|
|
4499
|
-
explain <rule-id> Show rationale, deletion test, and bad/trap/good examples
|
|
4500
|
-
init Create starter .dislop.json and gitignore .dislop.local.json
|
|
4501
|
-
|
|
4502
|
-
Browse rules & style:
|
|
4503
|
-
catalog [query] Search the 53-rule AI-slop catalog (alias: search)
|
|
4504
|
-
packs List bundled rule packs and supported formats
|
|
4505
|
-
patterns [file | -] Run multi-angle extended pattern-bank scan
|
|
4506
|
-
voice [paths... | -] Extract offline dislop.voice/1 writing profile
|
|
4507
|
-
|
|
4508
|
-
Agent & review:
|
|
4509
|
-
review [file | -] Multi-layer review (--offline | --endpoint <url> | --provider openai|gemini|local)
|
|
4510
|
-
apply Apply review edits with --review-file and --source-file
|
|
4511
|
-
--mcp Run local stdio MCP server (7 offline tools)
|
|
4512
|
-
resources Show bundled packs, static agent links, and Official Cloud MCP
|
|
4513
|
-
|
|
4514
|
-
Diagnostics & optional local models:
|
|
4515
|
-
doctor [--online] Check 3-layer readiness (Skill, Local CLI/ML, BYOK env, config, and optional Cloud ping)
|
|
4516
|
-
model [action] Manage/score Pocket ML & optional local models (status|score|install|import|remove|deslop)
|
|
4517
|
-
pack-test Validate Pack Schema v2 manifests and embedded fixtures
|
|
4518
|
-
|
|
4519
|
-
Exit codes: 0 clean | 1 findings >= --fail-on | 2 usage, config, or unreadable file error
|
|
4520
|
-
Example: dislop check draft.md --deep`);
|
|
4521
|
-
}
|
|
4522
|
-
|
|
4523
|
-
async function main() {
|
|
4524
|
-
const argv = process.argv.slice(2);
|
|
4525
|
-
const packs = loadAllPacks();
|
|
4526
|
-
const patternByRuleId = loadPatternLibrary();
|
|
4527
|
-
|
|
4528
|
-
if (argv.includes("--mcp")) {
|
|
4529
|
-
runMcpServer(packs, patternByRuleId);
|
|
4530
|
-
return;
|
|
4531
|
-
}
|
|
4532
|
-
if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help" || argv[0] === "help") {
|
|
4533
|
-
if (argv[0] === "help" && argv[1]) {
|
|
4534
|
-
if (COMMAND_SPECS[argv[1]]) {
|
|
4535
|
-
printSubcommandHelp(argv[1]);
|
|
4536
|
-
return;
|
|
4537
|
-
}
|
|
4538
|
-
console.error(`dislop: unknown command '${argv[1]}'. Run 'dislop --help' for usage.`);
|
|
4539
|
-
process.exit(2);
|
|
4540
|
-
}
|
|
4541
|
-
printHelp();
|
|
4542
|
-
return;
|
|
4543
|
-
}
|
|
4544
|
-
if (argv[0] === "-v" || argv[0] === "--version") {
|
|
4545
|
-
console.log(ENGINE_VERSION);
|
|
4546
|
-
return;
|
|
4547
|
-
}
|
|
4548
|
-
|
|
4549
|
-
const cmd = argv[0];
|
|
4550
|
-
const rest = argv.slice(1);
|
|
4551
|
-
if (cmd === "check") return runCheck(rest, packs);
|
|
4552
|
-
if (cmd === "verify") return runVerify(rest, packs);
|
|
4553
|
-
if (cmd === "review" || cmd === "apply") {
|
|
4554
|
-
try {
|
|
4555
|
-
if (cmd === "review") return await runReview(rest, packs);
|
|
4556
|
-
const { flags, positional } = parseFlags(rest, "apply");
|
|
4557
|
-
if (flags.help) return printSubcommandHelp("apply");
|
|
4558
|
-
if (!flags["review-file"] || !flags["source-file"] || positional.length) {
|
|
4559
|
-
throw Error("specify --review-file and --source-file");
|
|
4560
|
-
}
|
|
4561
|
-
const report = JSON.parse(fs.readFileSync(flags["review-file"], "utf8"));
|
|
4562
|
-
return applyReview(report, flags["source-file"], flags);
|
|
4563
|
-
} catch (error) {
|
|
4564
|
-
console.error(`dislop ${cmd}: ${error.message}`);
|
|
4565
|
-
process.exitCode = 2;
|
|
4566
|
-
return;
|
|
4567
|
-
}
|
|
4568
|
-
}
|
|
4569
|
-
if (cmd === "voice") return runVoice(rest);
|
|
4570
|
-
if (cmd === "doctor") return await runDoctor(rest, packs);
|
|
4571
|
-
if (cmd === "model") return await runModel(rest, packs, "model");
|
|
4572
|
-
if (cmd === "setup") return await runModel(["setup", ...rest], packs, "setup");
|
|
4573
|
-
if (cmd === "deslop") {
|
|
4574
|
-
const { flags, positional } = parseFlags(rest, "deslop");
|
|
4575
|
-
if (flags.help) {
|
|
4576
|
-
printSubcommandHelp("deslop");
|
|
4577
|
-
return;
|
|
4578
|
-
}
|
|
4579
|
-
if (!flags.local) {
|
|
4580
|
-
console.error("dislop deslop: pass --local to run with a loopback local small model (0 external upload).");
|
|
4581
|
-
process.exit(2);
|
|
4582
|
-
}
|
|
4583
|
-
return await runLocalDeslopCli(positional[0] || "-", flags, packs);
|
|
4584
|
-
}
|
|
4585
|
-
if (cmd === "explain") return runExplain(rest, packs, patternByRuleId);
|
|
4586
|
-
if (cmd === "catalog" || cmd === "search") return runCatalog(rest, packs, patternByRuleId);
|
|
4587
|
-
if (cmd === "patterns") return runPatterns(rest);
|
|
4588
|
-
if (cmd === "packs") return runPacks(rest, packs);
|
|
4589
|
-
if (cmd === "resources") return runResources(rest, packs);
|
|
4590
|
-
if (cmd === "pack-test") return runPackTest(rest, packs);
|
|
4591
|
-
if (cmd === "init") return runInit(rest);
|
|
4592
|
-
|
|
4593
|
-
console.error(`dislop: unknown command '${cmd}'. Run 'dislop --help' for usage.`);
|
|
4594
|
-
process.exit(2);
|
|
4595
|
-
}
|
|
4596
|
-
|
|
4597
|
-
main();
|