dislop 0.9.0 → 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.
Files changed (124) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +7 -8
  4. package/.cursor-plugin/plugin.json +2 -3
  5. package/.pre-commit-hooks.yaml +5 -12
  6. package/PRODUCT.md +19 -57
  7. package/README.md +360 -252
  8. package/README.zh-CN.md +390 -240
  9. package/action.yml +30 -39
  10. package/bin/dislop-mcp.mjs +3 -4
  11. package/bin/dislop.mjs +4 -4582
  12. package/gemini-extension.json +2 -2
  13. package/llms-install.md +68 -0
  14. package/package.json +17 -55
  15. package/packs/common/artifact-qa/pack.json +5 -0
  16. package/packs/common/artifact-qa/prompts/rules.md +11 -0
  17. package/packs/common/artifact-qa/scripts/index.mjs +173 -0
  18. package/packs/common/slide-deck/pack.json +6 -0
  19. package/packs/common/slide-deck/prompts/rules.md +11 -0
  20. package/packs/common/slide-deck/scripts/index.mjs +62 -0
  21. package/packs/common/web-ui/pack.json +6 -0
  22. package/packs/common/web-ui/prompts/rules.md +11 -0
  23. package/packs/common/web-ui/scripts/index.mjs +80 -0
  24. package/packs/en/artifact-qa/pack.json +6 -0
  25. package/packs/en/artifact-qa/prompts/rules.md +14 -0
  26. package/packs/en/artifact-qa/scripts/index.mjs +90 -0
  27. package/packs/en/prose/pack.json +7 -0
  28. package/packs/en/prose/prompts/rules.md +26 -0
  29. package/packs/en/prose/scripts/index.mjs +290 -0
  30. package/packs/en/slide-deck/pack.json +7 -0
  31. package/packs/en/slide-deck/prompts/rules.md +17 -0
  32. package/packs/en/slide-deck/scripts/index.mjs +81 -0
  33. package/packs/en/web-ui/pack.json +7 -0
  34. package/packs/en/web-ui/prompts/rules.md +20 -0
  35. package/packs/en/web-ui/scripts/index.mjs +103 -0
  36. package/packs/zh/artifact-qa/pack.json +6 -0
  37. package/packs/zh/artifact-qa/prompts/rules.md +14 -0
  38. package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
  39. package/packs/zh/prose/pack.json +7 -0
  40. package/packs/zh/prose/prompts/rules.md +26 -0
  41. package/packs/zh/prose/scripts/index.mjs +305 -0
  42. package/packs/zh/slide-deck/pack.json +7 -0
  43. package/packs/zh/slide-deck/prompts/rules.md +17 -0
  44. package/packs/zh/slide-deck/scripts/index.mjs +75 -0
  45. package/packs/zh/web-ui/pack.json +7 -0
  46. package/packs/zh/web-ui/prompts/rules.md +20 -0
  47. package/packs/zh/web-ui/scripts/index.mjs +98 -0
  48. package/plugin.json +5 -6
  49. package/server.json +8 -2
  50. package/skills/deslop-docs/SKILL.md +10 -8
  51. package/skills/deslop-slides-docx/SKILL.md +7 -8
  52. package/skills/deslop-verify/SKILL.md +7 -8
  53. package/skills/deslop-web-ui/SKILL.md +7 -8
  54. package/skills/dislop/SKILL.md +16 -28
  55. package/skills/dislop/references/essay.md +1 -1
  56. package/skills/dislop/references/essay.zh-CN.md +1 -1
  57. package/skills/dislop/references/office.md +1 -1
  58. package/skills/dislop/references/office.zh-CN.md +1 -1
  59. package/skills/dislop/references/web-ui.md +1 -1
  60. package/skills/dislop/references/web-ui.zh-CN.md +1 -1
  61. package/skills/dislop/references/work-docs.md +1 -1
  62. package/skills/dislop/references/work-docs.zh-CN.md +1 -1
  63. package/src/cli-main.mjs +210 -0
  64. package/src/commands/check-fix.mjs +169 -0
  65. package/src/commands/doctor.mjs +110 -0
  66. package/src/commands/init.mjs +49 -0
  67. package/src/commands/login.mjs +82 -0
  68. package/src/commands/model.mjs +130 -0
  69. package/src/commands/packs.mjs +44 -0
  70. package/src/commands/verify.mjs +133 -0
  71. package/src/commands/voice.mjs +84 -0
  72. package/src/kernel/config.mjs +232 -0
  73. package/src/kernel/document-model.mjs +1412 -0
  74. package/src/kernel/fact-gate.mjs +615 -0
  75. package/src/kernel/file-discovery.mjs +139 -0
  76. package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
  77. package/src/kernel/pack-loader.mjs +715 -0
  78. package/src/kernel/patcher.mjs +341 -0
  79. package/src/kernel/pipeline.mjs +267 -0
  80. package/src/kernel/prompt-assembler.mjs +307 -0
  81. package/src/kernel/voice-profile.mjs +177 -0
  82. package/src/mcp/stdio-server.mjs +372 -0
  83. package/src/runners/auto-fix.mjs +59 -0
  84. package/src/runners/interactive-tty.mjs +461 -0
  85. package/src/runners/reporters.mjs +256 -0
  86. package/src/runtime/chunker.mjs +87 -0
  87. package/src/runtime/json-extract.mjs +144 -0
  88. package/src/runtime/privacy-gate.mjs +97 -0
  89. package/src/runtime/providers/anthropic.mjs +65 -0
  90. package/src/runtime/providers/cloud.mjs +136 -0
  91. package/src/runtime/providers/gemini.mjs +91 -0
  92. package/src/runtime/providers/local-model.mjs +139 -0
  93. package/src/runtime/providers/openai-compat.mjs +130 -0
  94. package/src/runtime/router.mjs +315 -0
  95. package/src/sdk/index.mjs +137 -0
  96. package/models/manifest.json +0 -90
  97. package/models/pocket-slop-v1.json +0 -1
  98. package/packs/business-brief/pack.json +0 -937
  99. package/packs/core/pack.json +0 -209
  100. package/packs/deck-and-ui/pack.json +0 -539
  101. package/packs/engineering-spec/pack.json +0 -144
  102. package/packs/executive-deck/pack.json +0 -98
  103. package/packs/literary-essay/pack.json +0 -344
  104. package/packs/regulated-comms/pack.json +0 -99
  105. package/patterns/ai-tic-rubric.json +0 -252
  106. package/patterns/banks/composite-fusion.json +0 -48
  107. package/patterns/banks/discourse-rhythm.json +0 -95
  108. package/patterns/banks/lexical-signals.json +0 -92
  109. package/patterns/banks/syntactic-frames.json +0 -52
  110. package/patterns/banks/visual-deck.json +0 -44
  111. package/patterns/dimensions/artifacts.json +0 -121
  112. package/patterns/dimensions/discourse.json +0 -438
  113. package/patterns/dimensions/lexical.json +0 -198
  114. package/patterns/dimensions/rhythm.json +0 -258
  115. package/patterns/dimensions/syntactic.json +0 -285
  116. package/patterns/dimensions/visual-and-deck.json +0 -530
  117. package/patterns/taxonomy.json +0 -112
  118. package/src/core.mjs +0 -5497
  119. package/src/dislop/review-picker.vim +0 -114
  120. package/src/local-model.mjs +0 -997
  121. package/src/pattern-engine.mjs +0 -1003
  122. package/src/pocket-model.mjs +0 -729
  123. package/src/review-apply.mjs +0 -151
  124. package/src/review-client.mjs +0 -1073
@@ -1,997 +0,0 @@
1
- /**
2
- * Hardware-aware Local Model Manager & Loopback Self-Healing Runner (`dislop.local-model/1`).
3
- * Zero external dependencies:
4
- * - Bundled Default: `pocket-slop-v1.json` (~15 KB gz, 0 network, <0.5 ms)
5
- * - Optional Local SLMs (`fast` | `balanced` | `quality`): 0.6B / 1.7B / 4B GGUF tiers
6
- * with hardware guardrails, SHA-256 confined import, loopback-only TLS/HTTP enforcement,
7
- * and unit-aware `verifyRevision` fact-lock fallback.
8
- */
9
-
10
- import crypto from "node:crypto";
11
- import fs from "node:fs";
12
- import http from "node:http";
13
- import https from "node:https";
14
- import os from "node:os";
15
- import path from "node:path";
16
- import { spawnSync } from "node:child_process";
17
- import { fileURLToPath } from "node:url";
18
-
19
- import { auditText, extractProtectedFacts, getScenarioStrategy, verifyRevision } from "./core.mjs";
20
- import { loadPocketModelBundle, scorePocketSpan } from "./pocket-model.mjs";
21
-
22
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
- const MANIFEST_CANDIDATES = [
24
- path.resolve(__dirname, "..", "models", "manifest.json"),
25
- path.resolve(__dirname, "models", "manifest.json"),
26
- ];
27
-
28
- const VALID_PROVIDERS = new Set(["ollama", "gguf"]);
29
-
30
- export const LOCAL_MODEL_TIERS = {
31
- none: {
32
- tier: "none",
33
- kind: "bundled-only",
34
- modelId: null,
35
- approxDownloadMb: 0,
36
- minRamGb: 0,
37
- minFreeDiskGb: 0,
38
- license: "Apache-2.0",
39
- summary: {
40
- en: "Built-in deterministic engine + bundled 15 KB Pocket ML ensemble (all 7 rule packs + 53 patterns + 5-axis telemetry included, 0 MB extra download).",
41
- zh: "仅使用随包内置的确定性引擎与 15 KB 传统集成模型(含全部 7 套规则包、53 条模式与 5 轴统计,无需额外下载)。",
42
- },
43
- installHint: null,
44
- },
45
- fast: {
46
- tier: "fast",
47
- kind: "local-slm-gguf",
48
- modelId: "qwen3:0.6b",
49
- approxDownloadMb: 520,
50
- minRamGb: 8,
51
- minFreeDiskGb: 2.0,
52
- license: "Apache-2.0",
53
- summary: {
54
- en: "Compact 0.6B bilingual model (~520 MB) for grey-zone filler triage on 8 GB CPU machines.",
55
- zh: "轻量 0.6B 双语小模型(约 520 MB),适合 8 GB 内存笔记本做灰区空话辅助复核。",
56
- },
57
- installHint: "dislop model install --tier fast",
58
- },
59
- balanced: {
60
- tier: "balanced",
61
- kind: "local-slm-gguf",
62
- modelId: "qwen3:1.7b",
63
- approxDownloadMb: 1300,
64
- minRamGb: 8,
65
- minFreeDiskGb: 3.0,
66
- license: "Apache-2.0",
67
- summary: {
68
- en: "Balanced 1.7B bilingual model (~1.3 GB) for local structural review on 8 GB Apple Silicon or 16 GB RAM.",
69
- zh: "均衡 1.7B 双语小模型(约 1.3 GB),适合 8 GB Apple Silicon 或 16 GB 内存设备离线审校与锁数字改写。",
70
- },
71
- installHint: "dislop model install --tier balanced",
72
- },
73
- quality: {
74
- tier: "quality",
75
- kind: "local-slm-gguf",
76
- modelId: "qwen3:4b",
77
- approxDownloadMb: 2500,
78
- minRamGb: 16,
79
- minFreeDiskGb: 5.0,
80
- license: "Apache-2.0",
81
- summary: {
82
- en: "High-precision 4B bilingual model (~2.5 GB) for local review & fact-locked paragraph cleanup on >= 16 GB Apple Silicon / GPU.",
83
- zh: "高精度 4B 双语小模型(约 2.5 GB),适合 >= 16 GB Apple Silicon 或独显机器做本地深度审校与锁数字改写。",
84
- },
85
- installHint: "dislop model install --tier quality",
86
- },
87
- };
88
-
89
- export function loadModelsManifest() {
90
- for (const p of MANIFEST_CANDIDATES) {
91
- if (fs.existsSync(p)) {
92
- return JSON.parse(fs.readFileSync(p, "utf8"));
93
- }
94
- }
95
- return { schema: "dislop.models-manifest/1", version: "1.0.0", bundled: [], optionalTiers: LOCAL_MODEL_TIERS };
96
- }
97
-
98
- export function getModelCacheDir(overrideDir = null) {
99
- if (overrideDir) return path.resolve(overrideDir);
100
- if (process.env.DISLOP_MODEL_DIR) return path.resolve(process.env.DISLOP_MODEL_DIR);
101
- if (process.platform === "linux" && process.env.XDG_CACHE_HOME) {
102
- return path.join(process.env.XDG_CACHE_HOME, "dislop", "models");
103
- }
104
- return path.join(os.homedir(), ".cache", "dislop", "models");
105
- }
106
-
107
- function readRegistry(cacheDir) {
108
- const regPath = path.join(cacheDir, "registry.json");
109
- if (!fs.existsSync(regPath)) return { version: 1, models: [] };
110
- try {
111
- const parsed = JSON.parse(fs.readFileSync(regPath, "utf8"));
112
- return Array.isArray(parsed.models) ? parsed : { version: 1, models: [] };
113
- } catch {
114
- return { version: 1, models: [] };
115
- }
116
- }
117
-
118
- function writeRegistry(cacheDir, reg) {
119
- fs.mkdirSync(cacheDir, { recursive: true });
120
- const realCache = fs.realpathSync(cacheDir);
121
- const regPath = path.join(realCache, "registry.json");
122
- if (fs.existsSync(regPath) && fs.lstatSync(regPath).isSymbolicLink()) {
123
- throw new Error("Refusing to write registry.json through a symbolic link.");
124
- }
125
- const tmpPath = path.join(realCache, `.registry.${crypto.randomBytes(6).toString("hex")}.tmp`);
126
- fs.writeFileSync(tmpPath, JSON.stringify(reg, null, 2) + "\n", { encoding: "utf8", flag: "wx", mode: 0o600 });
127
- fs.renameSync(tmpPath, regPath);
128
- }
129
-
130
- export function listInstalledModels(cacheDir = null) {
131
- const dir = getModelCacheDir(cacheDir);
132
- const reg = readRegistry(dir);
133
- return reg.models.map((entry) => ({
134
- ...entry,
135
- exists: entry.provider === "ollama" ? true : Boolean(entry.path && fs.existsSync(entry.path)),
136
- }));
137
- }
138
-
139
- export function probeHardware(overrides = null) {
140
- if (overrides) {
141
- return { ...overrides };
142
- }
143
- const platform = os.platform();
144
- const arch = os.arch();
145
- const cpus = os.cpus() || [];
146
- const cpuModel = cpus[0]?.model ? String(cpus[0].model).trim() : "unknown";
147
- const cpuCount = cpus.length || 1;
148
- const totalMemoryGb = Number((os.totalmem() / 1024 ** 3).toFixed(1));
149
- const isCi = Boolean(process.env.CI && process.env.CI !== "0" && process.env.CI !== "false");
150
- const isAppleSilicon = platform === "darwin" && arch === "arm64";
151
-
152
- let freeDiskGb = null;
153
- try {
154
- if (typeof fs.statfsSync === "function") {
155
- const st = fs.statfsSync(os.homedir());
156
- freeDiskGb = Number(((Number(st.bavail) * Number(st.bsize)) / 1024 ** 3).toFixed(1));
157
- }
158
- } catch {
159
- freeDiskGb = null;
160
- }
161
-
162
- const usableModelMemoryGb = Number((totalMemoryGb * (isAppleSilicon ? 0.62 : 0.38)).toFixed(1));
163
- return {
164
- platform,
165
- arch,
166
- cpuModel,
167
- cpuCount,
168
- totalMemoryGb,
169
- usableModelMemoryGb,
170
- freeDiskGb,
171
- isAppleSilicon,
172
- isCi,
173
- };
174
- }
175
-
176
- export function recommendModelTier(hw) {
177
- if (hw.isCi || hw.totalMemoryGb < 8 || (hw.freeDiskGb !== null && hw.freeDiskGb < 2.0)) {
178
- const reasonEn = hw.isCi
179
- ? "CI environment detected; keep fast zero-download deterministic + bundled 15 KB Pocket ML checks."
180
- : hw.freeDiskGb !== null && hw.freeDiskGb < 2.0
181
- ? `Low free disk space (${hw.freeDiskGb} GB); skipping multi-hundred-MB model weights (bundled 15 KB Pocket ML is already active).`
182
- : `System RAM (${hw.totalMemoryGb} GB) is below 8 GB; built-in rules + 15 KB Pocket ML run in < 5ms with 0 extra memory.`;
183
- const reasonZh = hw.isCi
184
- ? "检测到 CI 流水线环境,直接使用内置规则引擎与 15 KB 传统集成模型最快最稳。"
185
- : hw.freeDiskGb !== null && hw.freeDiskGb < 2.0
186
- ? `剩余磁盘空间较少(${hw.freeDiskGb} GB),跳过百 MB 级模型下载(内置 15 KB 传统集成模型已就绪)。`
187
- : `当前内存(${hw.totalMemoryGb} GB)低于 8 GB,内置规则包与 15 KB 传统集成模型已可完整离线工作。`;
188
- return { ...LOCAL_MODEL_TIERS.none, reason: { en: reasonEn, zh: reasonZh } };
189
- }
190
-
191
- if (hw.isAppleSilicon && hw.totalMemoryGb >= 16 && (hw.freeDiskGb === null || hw.freeDiskGb >= 5.0)) {
192
- return {
193
- ...LOCAL_MODEL_TIERS.quality,
194
- reason: {
195
- en: `Apple Silicon with ${hw.totalMemoryGb} GB unified memory (~${hw.usableModelMemoryGb} GB model budget) comfortably runs 4B Q4_K_M locally.`,
196
- zh: `检测到 ${hw.totalMemoryGb} GB 统一内存的 Apple Silicon(可用模型预算约 ${hw.usableModelMemoryGb} GB),可流畅选装 4B 本地小模型。`,
197
- },
198
- };
199
- }
200
-
201
- if ((hw.isAppleSilicon && hw.totalMemoryGb >= 8) || hw.totalMemoryGb >= 16) {
202
- return {
203
- ...LOCAL_MODEL_TIERS.balanced,
204
- reason: {
205
- en: `${hw.totalMemoryGb} GB RAM fits the 1.7B Q4_K_M tier (~1.3 GB) without starving IDE/browser memory.`,
206
- zh: `${hw.totalMemoryGb} GB 内存适合选装 1.7B 均衡档(约 1.3 GB),兼顾响应速度与日常开发内存余量。`,
207
- },
208
- };
209
- }
210
-
211
- return {
212
- ...LOCAL_MODEL_TIERS.fast,
213
- reason: {
214
- en: `${hw.totalMemoryGb} GB CPU system matches the lightweight 0.6B tier (~520 MB).`,
215
- zh: `${hw.totalMemoryGb} GB 内存通用机型建议选装轻量 0.6B 档(约 520 MB),避免拖慢系统。`,
216
- },
217
- };
218
- }
219
-
220
- function probeLoopbackJson(port, urlPath, timeoutMs = 250) {
221
- return new Promise((resolve) => {
222
- const req = http.get(
223
- { host: "127.0.0.1", port, path: urlPath, timeout: timeoutMs, agent: false },
224
- (res) => {
225
- if (res.statusCode !== 200) {
226
- res.resume();
227
- resolve(null);
228
- return;
229
- }
230
- const chunks = [];
231
- res.on("data", (c) => chunks.push(c));
232
- res.on("end", () => {
233
- try {
234
- resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
235
- } catch {
236
- resolve(null);
237
- }
238
- });
239
- }
240
- );
241
- req.on("timeout", () => {
242
- req.destroy();
243
- resolve(null);
244
- });
245
- req.on("error", () => resolve(null));
246
- });
247
- }
248
-
249
- export async function discoverLocalRunners({ timeoutMs = 250 } = {}) {
250
- const runners = [];
251
- const ollama = await probeLoopbackJson(11434, "/api/tags", timeoutMs);
252
- if (ollama && Array.isArray(ollama.models)) {
253
- runners.push({
254
- kind: "ollama",
255
- endpoint: "http://127.0.0.1:11434",
256
- models: ollama.models.map((m) => m.name).slice(0, 20),
257
- });
258
- }
259
- const llamaServer = await probeLoopbackJson(8080, "/v1/models", timeoutMs);
260
- if (llamaServer && Array.isArray(llamaServer.data)) {
261
- runners.push({
262
- kind: "openai-compatible-local",
263
- endpoint: "http://127.0.0.1:8080",
264
- models: llamaServer.data.map((m) => m.id).slice(0, 20),
265
- });
266
- }
267
- return runners;
268
- }
269
-
270
- export async function buildModelStatusReport({
271
- packsCount = 7,
272
- rulesCount = 42,
273
- probeLoopback = true,
274
- hwOverrides = null,
275
- cacheDir = null,
276
- } = {}) {
277
- const hardware = probeHardware(hwOverrides);
278
- const recommendation = recommendModelTier(hardware);
279
- const localRunners = probeLoopback ? await discoverLocalRunners() : [];
280
- const bundle = loadPocketModelBundle();
281
- const manifest = loadModelsManifest();
282
- const resolvedCache = getModelCacheDir(cacheDir);
283
- const installedModels = listInstalledModels(resolvedCache);
284
-
285
- return {
286
- schema: "dislop.local-model/1",
287
- builtinDeterministic: {
288
- ready: true,
289
- bundledPacks: packsCount,
290
- bundledRules: rulesCount,
291
- networkCallsDuringCheck: 0,
292
- },
293
- bundledModels: [
294
- {
295
- id: "pocket-slop-v1",
296
- schema: bundle.schema,
297
- version: bundle.version,
298
- ready: true,
299
- approxGzipKb: manifest.bundled?.[0]?.approxGzipKb ?? 15,
300
- runtimeDeps: "none",
301
- heads: ["pocket-slop-ensemble", "pocket-pack-router"],
302
- },
303
- ],
304
- modelCacheDir: resolvedCache,
305
- installedModels,
306
- hardware,
307
- recommendation,
308
- localRunners,
309
- };
310
- }
311
-
312
- function hasOllamaCli() {
313
- try {
314
- const r = spawnSync("ollama", ["--version"], { encoding: "utf8", timeout: 2500 });
315
- return r.status === 0;
316
- } catch {
317
- return false;
318
- }
319
- }
320
-
321
- export function installOptionalModel({
322
- tier = "auto",
323
- provider = "ollama",
324
- force = false,
325
- dryRun = false,
326
- cacheDir = null,
327
- hwOverrides = null,
328
- } = {}) {
329
- if (!VALID_PROVIDERS.has(provider)) {
330
- return {
331
- ok: false,
332
- error: `Unknown provider '${provider}'. Supported providers: ollama, gguf.`,
333
- };
334
- }
335
- const hw = probeHardware(hwOverrides);
336
- const rec = recommendModelTier(hw);
337
- const resolvedTierName = tier === "auto" ? rec.tier : tier;
338
- const spec = Object.hasOwn(LOCAL_MODEL_TIERS, resolvedTierName) ? LOCAL_MODEL_TIERS[resolvedTierName] : null;
339
- if (!spec) {
340
- return {
341
- ok: false,
342
- error: `Unknown model tier '${resolvedTierName}'. Choose one of: none, fast, balanced, quality, auto.`,
343
- };
344
- }
345
-
346
- const resolvedCache = getModelCacheDir(cacheDir);
347
-
348
- if (resolvedTierName === "none") {
349
- return {
350
- ok: true,
351
- action: "none",
352
- tier: "none",
353
- modelId: null,
354
- bundledReady: true,
355
- message: {
356
- en: "Built-in deterministic rules and bundled 15 KB Pocket ML suite are already installed and ready.",
357
- zh: "内置规则包与随包 15 KB 传统集成模型已就绪,无需额外下载大体积权重。",
358
- },
359
- };
360
- }
361
-
362
- const minRam = spec.minRamGb || 0;
363
- const minDisk = spec.minFreeDiskGb || 0;
364
- const ramTooLow = hw.totalMemoryGb < minRam;
365
- const diskTooLow = hw.freeDiskGb !== null && hw.freeDiskGb < minDisk;
366
-
367
- if ((ramTooLow || diskTooLow) && !force) {
368
- const reasonEn = ramTooLow
369
- ? `Tier '${resolvedTierName}' (~${spec.approxDownloadMb} MB) requires >= ${minRam} GB RAM, but this machine has ${hw.totalMemoryGb} GB.`
370
- : `Tier '${resolvedTierName}' requires >= ${minDisk} GB free disk, but only ${hw.freeDiskGb} GB is available.`;
371
- const reasonZh = ramTooLow
372
- ? `档位「${resolvedTierName}」(约 ${spec.approxDownloadMb} MB)建议至少 ${minRam} GB 内存,当前设备为 ${hw.totalMemoryGb} GB。`
373
- : `档位「${resolvedTierName}」需要至少 ${minDisk} GB 可用磁盘空间,当前仅剩 ${hw.freeDiskGb} GB。`;
374
- return {
375
- ok: false,
376
- blockedByHardware: true,
377
- tier: resolvedTierName,
378
- recommendedTier: rec.tier,
379
- warning: {
380
- en: `${reasonEn} Recommended tier: '${rec.tier}'. Pass --force to override.`,
381
- zh: `${reasonZh} 当前推荐档位:「${rec.tier}」。如仍需安装请加 --force。`,
382
- },
383
- };
384
- }
385
-
386
- const plannedCmd =
387
- provider === "gguf"
388
- ? `dislop model import <file.gguf> --tier ${resolvedTierName}`
389
- : `ollama pull ${spec.modelId}`;
390
-
391
- if (dryRun) {
392
- return {
393
- ok: true,
394
- dryRun: true,
395
- tier: resolvedTierName,
396
- modelId: spec.modelId,
397
- provider,
398
- approxDownloadMb: spec.approxDownloadMb,
399
- modelCacheDir: resolvedCache,
400
- command: plannedCmd,
401
- hardwareCheck: ramTooLow || diskTooLow ? "forced-override" : "passed",
402
- };
403
- }
404
-
405
- if (provider === "gguf") {
406
- return {
407
- ok: false,
408
- missingWeights: true,
409
- tier: resolvedTierName,
410
- modelId: spec.modelId,
411
- message: {
412
- en: `Pass a local GGUF file to import with SHA-256 verification: 'dislop model import <file.gguf> --tier ${resolvedTierName}'.`,
413
- zh: `请指定本地 GGUF 权重文件执行离线校验导入:'dislop model import <file.gguf> --tier ${resolvedTierName}'。`,
414
- },
415
- };
416
- }
417
-
418
- if (!hasOllamaCli()) {
419
- return {
420
- ok: false,
421
- missingRunner: true,
422
- tier: resolvedTierName,
423
- modelId: spec.modelId,
424
- message: {
425
- en: `Local runner 'ollama' was not found in PATH. Install Ollama (https://ollama.com) or import an offline GGUF weight file via 'dislop model import <file.gguf> --tier ${resolvedTierName}'.`,
426
- zh: `未在 PATH 中检测到 ollama。可先安装 Ollama,或在内网离线环境通过 'dislop model import <file.gguf> --tier ${resolvedTierName}' 直接导入权重文件。`,
427
- },
428
- };
429
- }
430
-
431
- const pull = spawnSync("ollama", ["pull", spec.modelId], { stdio: "inherit" });
432
- if (pull.status !== 0) {
433
- return {
434
- ok: false,
435
- tier: resolvedTierName,
436
- modelId: spec.modelId,
437
- error: `ollama pull ${spec.modelId} exited with code ${pull.status}`,
438
- };
439
- }
440
-
441
- const reg = readRegistry(resolvedCache);
442
- reg.models = reg.models.filter((m) => !(m.tier === resolvedTierName && m.provider === "ollama"));
443
- reg.models.push({
444
- id: spec.modelId,
445
- tier: resolvedTierName,
446
- provider: "ollama",
447
- path: null,
448
- sizeBytes: spec.approxDownloadMb * 1024 * 1024,
449
- sha256: null,
450
- installedAt: new Date().toISOString(),
451
- });
452
- writeRegistry(resolvedCache, reg);
453
-
454
- return {
455
- ok: true,
456
- tier: resolvedTierName,
457
- modelId: spec.modelId,
458
- provider: "ollama",
459
- modelCacheDir: resolvedCache,
460
- };
461
- }
462
-
463
- function sha256FileSync(filePath) {
464
- const hash = crypto.createHash("sha256");
465
- const fd = fs.openSync(filePath, "r");
466
- const buf = Buffer.alloc(65536);
467
- try {
468
- let bytesRead = 0;
469
- while ((bytesRead = fs.readSync(fd, buf, 0, buf.length, null)) > 0) {
470
- hash.update(buf.subarray(0, bytesRead));
471
- }
472
- } finally {
473
- fs.closeSync(fd);
474
- }
475
- return hash.digest("hex");
476
- }
477
-
478
- export function importLocalModelFile({
479
- filePath,
480
- tier = "custom",
481
- expectedSha256 = null,
482
- copyFile = true,
483
- cacheDir = null,
484
- } = {}) {
485
- const srcAbs = path.resolve(String(filePath || ""));
486
- if (!fs.existsSync(srcAbs) || !fs.statSync(srcAbs).isFile()) {
487
- return { ok: false, error: `Model file not found: ${filePath}` };
488
- }
489
- const fileName = path.basename(srcAbs);
490
- const ext = path.extname(fileName).toLowerCase();
491
- if (fileName.toLowerCase() === "registry.json" || ![".gguf", ".onnx", ".bin"].includes(ext)) {
492
- return { ok: false, error: `Unsupported model file '${fileName}' (expected .gguf, .onnx, or .bin).` };
493
- }
494
-
495
- const actualSha = sha256FileSync(srcAbs);
496
- if (expectedSha256 && actualSha.toLowerCase() !== String(expectedSha256).trim().toLowerCase()) {
497
- return {
498
- ok: false,
499
- reason: "sha256-mismatch",
500
- expectedSha256: String(expectedSha256).trim().toLowerCase(),
501
- actualSha256: actualSha,
502
- error: `SHA-256 mismatch for ${fileName}`,
503
- };
504
- }
505
-
506
- const resolvedCache = getModelCacheDir(cacheDir);
507
- fs.mkdirSync(resolvedCache, { recursive: true });
508
- const realCache = fs.realpathSync(resolvedCache);
509
- const destAbs = copyFile ? path.join(realCache, fileName) : fs.realpathSync(srcAbs);
510
-
511
- if (copyFile && fs.realpathSync(srcAbs) !== destAbs) {
512
- if (fs.existsSync(destAbs) && fs.lstatSync(destAbs).isSymbolicLink()) {
513
- return { ok: false, error: `Refusing to overwrite symbolic link in model cache: ${destAbs}` };
514
- }
515
- const nonce = crypto.randomBytes(6).toString("hex");
516
- const tmpDest = path.join(realCache, `.${fileName}.${nonce}.part`);
517
- fs.copyFileSync(srcAbs, tmpDest, fs.constants.COPYFILE_EXCL);
518
- fs.renameSync(tmpDest, destAbs);
519
- }
520
-
521
- const sizeBytes = fs.statSync(destAbs).size;
522
- const reg = readRegistry(realCache);
523
- reg.models = reg.models.filter((m) => m.id !== fileName && m.path !== destAbs);
524
- const entry = {
525
- id: fileName,
526
- tier,
527
- provider: ext === ".onnx" ? "onnx-file" : "gguf-file",
528
- path: destAbs,
529
- sizeBytes,
530
- sha256: actualSha,
531
- installedAt: new Date().toISOString(),
532
- };
533
- reg.models.push(entry);
534
- writeRegistry(realCache, reg);
535
-
536
- return {
537
- ok: true,
538
- modelCacheDir: realCache,
539
- imported: entry,
540
- };
541
- }
542
-
543
- export function removeInstalledModel({ target, cacheDir = null } = {}) {
544
- const resolvedCache = getModelCacheDir(cacheDir);
545
- if (!fs.existsSync(resolvedCache)) {
546
- return { ok: false, error: `No cached models found in ${resolvedCache}` };
547
- }
548
- const realCache = fs.realpathSync(resolvedCache);
549
- const reg = readRegistry(realCache);
550
- const key = String(target || "").trim();
551
- if (!key) {
552
- return { ok: false, error: "Specify a tier or model id to remove." };
553
- }
554
- const removed = [];
555
- const kept = [];
556
- for (const m of reg.models) {
557
- if (m.tier === key || m.id === key) {
558
- if (m.provider === "ollama" && m.id && hasOllamaCli()) {
559
- spawnSync("ollama", ["rm", m.id], { stdio: "ignore" });
560
- }
561
- if (m.path) {
562
- try {
563
- const parentDir = path.dirname(m.path);
564
- const baseName = path.basename(m.path);
565
- if (fs.existsSync(parentDir) && fs.realpathSync(parentDir) === realCache && baseName !== "registry.json") {
566
- const safeTarget = path.join(realCache, baseName);
567
- const st = fs.lstatSync(safeTarget);
568
- if (st.isFile() || st.isSymbolicLink()) {
569
- fs.unlinkSync(safeTarget);
570
- }
571
- }
572
- } catch {}
573
- }
574
- removed.push(m);
575
- } else {
576
- kept.push(m);
577
- }
578
- }
579
- writeRegistry(realCache, { version: 1, models: kept });
580
- return { ok: removed.length > 0, removedCount: removed.length, removed };
581
- }
582
-
583
- export function assertSafeLocalEndpoint(endpointUrl, { allowLan = false } = {}) {
584
- let parsed;
585
- try {
586
- parsed = new URL(endpointUrl);
587
- } catch {
588
- throw new Error(`Invalid local model endpoint URL: ${endpointUrl}`);
589
- }
590
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
591
- throw new Error(`Unsupported protocol '${parsed.protocol}' for local model endpoint.`);
592
- }
593
- const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
594
- const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "::1";
595
- if (!isLoopback && !allowLan) {
596
- throw new Error(
597
- `Refusing non-loopback endpoint '${host}' in --local mode (data must stay on 127.0.0.1). Pass --allow-lan only for trusted intranet servers.`
598
- );
599
- }
600
- return parsed;
601
- }
602
-
603
- function postJsonHttp(urlObj, payload, timeoutMs = 30000) {
604
- const body = Buffer.from(JSON.stringify(payload), "utf8");
605
- const isHttps = urlObj.protocol === "https:";
606
- const transport = isHttps ? https : http;
607
- const host = urlObj.hostname.replace(/^\[|\]$/g, "");
608
- const defaultPort = isHttps ? 443 : 80;
609
- const port = urlObj.port ? Number(urlObj.port) : defaultPort;
610
-
611
- return new Promise((resolve, reject) => {
612
- const req = transport.request(
613
- {
614
- hostname: host,
615
- port,
616
- path: urlObj.pathname + urlObj.search,
617
- method: "POST",
618
- headers: {
619
- "Content-Type": "application/json",
620
- "Content-Length": body.length,
621
- },
622
- timeout: timeoutMs,
623
- agent: false,
624
- },
625
- (res) => {
626
- const chunks = [];
627
- res.on("data", (c) => chunks.push(c));
628
- res.on("end", () => {
629
- const text = Buffer.concat(chunks).toString("utf8");
630
- if (res.statusCode < 200 || res.statusCode >= 300) {
631
- reject(new Error(`Local runner HTTP ${res.statusCode}: ${text.slice(0, 200)}`));
632
- return;
633
- }
634
- try {
635
- resolve(JSON.parse(text));
636
- } catch {
637
- reject(new Error(`Invalid JSON from local runner: ${text.slice(0, 200)}`));
638
- }
639
- });
640
- }
641
- );
642
- req.on("timeout", () => {
643
- req.destroy();
644
- reject(new Error(`Local model request timed out after ${timeoutMs}ms`));
645
- });
646
- req.on("error", (err) => reject(err));
647
- req.write(body);
648
- req.end();
649
- });
650
- }
651
-
652
- async function callLocalChatCompletion({ endpoint, kind, model, systemPrompt, userPrompt, timeoutMs = 30000, allowLan = false }) {
653
- const baseUrl = assertSafeLocalEndpoint(endpoint, { allowLan });
654
- if (kind === "ollama") {
655
- const target = new URL("/api/chat", baseUrl);
656
- const resp = await postJsonHttp(
657
- target,
658
- {
659
- model,
660
- stream: false,
661
- think: false,
662
- options: { temperature: 0.2, num_ctx: 4096 },
663
- messages: [
664
- { role: "system", content: systemPrompt },
665
- { role: "user", content: userPrompt },
666
- ],
667
- },
668
- timeoutMs
669
- );
670
- return String(resp?.message?.content || "").replace(/<think>[\s\S]*?<\/think>/gi, "").trim();
671
- }
672
-
673
- const target = new URL("/v1/chat/completions", baseUrl);
674
- const resp = await postJsonHttp(
675
- target,
676
- {
677
- model: model || "local-model",
678
- temperature: 0.2,
679
- max_tokens: 1024,
680
- messages: [
681
- { role: "system", content: systemPrompt },
682
- { role: "user", content: userPrompt },
683
- ],
684
- },
685
- timeoutMs
686
- );
687
- return String(resp?.choices?.[0]?.message?.content || "").replace(/<think>[\s\S]*?<\/think>/gi, "").trim();
688
- }
689
-
690
- const UNIT_EXTRACT_RE = /([0-9][0-9,]*(?:\.[0-9]+)?)\s*(%|ms|sec|seconds?|s|mins?|minutes?|hrs?|hours?|days?|kb|mb|gb|tb|qps|tps|rps|fps|px|毫秒|秒|分钟|小时|个月|天|年|倍|万|亿|美元|元|次|个|条|份|页|行|人|席)/gi;
691
-
692
- function canonicalizeUnit(u) {
693
- const low = String(u || "").toLowerCase();
694
- if (low === "s" || low === "sec" || low === "second" || low === "seconds" || low === "秒") return "s";
695
- if (low === "ms" || low === "毫秒") return "ms";
696
- if (low === "min" || low === "mins" || low === "minute" || low === "minutes" || low === "分钟") return "min";
697
- if (low === "hr" || low === "hrs" || low === "hour" || low === "hours" || low === "小时") return "h";
698
- if (low === "day" || low === "days" || low === "天") return "d";
699
- return low;
700
- }
701
-
702
- function extractNumberUnitMultiset(text) {
703
- const counts = new Map();
704
- const s = String(text || "");
705
- let m;
706
- UNIT_EXTRACT_RE.lastIndex = 0;
707
- while ((m = UNIT_EXTRACT_RE.exec(s)) !== null) {
708
- const num = m[1].replace(/,/g, "");
709
- const unit = canonicalizeUnit(m[2]);
710
- const key = `${num}:${unit}`;
711
- counts.set(key, (counts.get(key) || 0) + 1);
712
- }
713
- return counts;
714
- }
715
-
716
- export function verifyFactsWithUnits(beforeText, afterText, { modality = "markdown" } = {}) {
717
- const ledger = verifyRevision(beforeText, afterText, { modality, allowAdded: false });
718
- const beforeUnits = extractNumberUnitMultiset(beforeText);
719
- const afterUnits = extractNumberUnitMultiset(afterText);
720
- const unitMismatches = [];
721
- for (const [k, cnt] of beforeUnits.entries()) {
722
- if ((afterUnits.get(k) || 0) < cnt) {
723
- unitMismatches.push(k);
724
- }
725
- }
726
- return {
727
- ok: ledger.status === "preserved" && unitMismatches.length === 0,
728
- ledger,
729
- unitMismatches,
730
- };
731
- }
732
-
733
- function buildParagraphDeslopPrompt(
734
- paragraph,
735
- findings,
736
- pocketScore,
737
- protectedFacts,
738
- repairFeedback = null,
739
- { packId = "business-brief", register = "unspecified" } = {}
740
- ) {
741
- const isZh = /[\u4e00-\u9fff]/.test(paragraph);
742
- const strategy = getScenarioStrategy({ packId, register });
743
- const lockedTokens = protectedFacts.map((f) => f.raw);
744
- const ruleNotes = findings.map((f) => `- ${f.ruleId}: ${(isZh ? f.message?.zh : f.message?.en) || f.ruleId}`);
745
- const mlNotes = (pocketScore.topDrivers || []).map(
746
- (d) => `- ${isZh ? d.reason.zh : d.reason.en}`
747
- );
748
- const diag = [...ruleNotes, ...mlNotes].slice(0, 5).join("\n");
749
-
750
- if (isZh) {
751
- const sys = [
752
- `你是贴合当前写作场景(${strategy.label.zh})的审改编辑。`,
753
- `重点清除:${strategy.cut.zh}`,
754
- `必须保留:${strategy.protect.zh}`,
755
- `严禁改偏:${strategy.avoid.zh}`,
756
- "只输出改写后的纯正文段落,不加解释、不加引号、不加开头寒暄,严禁编造原句没有的数字,严禁篡改单位,严禁写成『不是……而是……』或三段分号排比。",
757
- ].join("\n");
758
- let usr = `请按「${strategy.label.zh}」场景要求改净下面段落,保留全部事实含义:\n\n【原段】\n${paragraph}\n`;
759
- if (diag) usr += `\n【检测到的问题】\n${diag}\n`;
760
- if (lockedTokens.length > 0) {
761
- usr += `\n【必须原样保留的数字、单位、限定词、代码与链接】\n${lockedTokens.join(" 、 ")}\n`;
762
- }
763
- if (repairFeedback) {
764
- usr += `\n【上一版改写未通过核验,请立即修正】\n${repairFeedback}\n`;
765
- }
766
- return { systemPrompt: sys, userPrompt: usr };
767
- }
768
-
769
- const sys = [
770
- `You are an editor tuned for ${strategy.label.en} (${strategy.id}).`,
771
- `Cut: ${strategy.cut.en}`,
772
- `Protect: ${strategy.protect.en}`,
773
- `Avoid: ${strategy.avoid.en}`,
774
- "Output ONLY the rewritten paragraph text—no preamble, no quotes, no invented numbers, no altered units, no semicolon tricolons, and no 'Not X, but Y' slogans.",
775
- ].join("\n");
776
- let usr = `Clean AI slop from this ${strategy.label.en} paragraph while preserving every fact:\n\n[Original]\n${paragraph}\n`;
777
- if (diag) usr += `\n[Detected issues]\n${diag}\n`;
778
- if (lockedTokens.length > 0) {
779
- usr += `\n[Must preserve verbatim (numbers, units, qualifiers, inline code, URLs)]\n${lockedTokens.join(" | ")}\n`;
780
- }
781
- if (repairFeedback) {
782
- usr += `\n[Previous rewrite failed verification — fix this]\n${repairFeedback}\n`;
783
- }
784
- return { systemPrompt: sys, userPrompt: usr };
785
- }
786
-
787
- function splitDocumentPreservingProtectedBlocks(raw) {
788
- const s = String(raw || "");
789
- const protectedBlockRe = /(<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->|```[\s\S]*?```|~~~[\s\S]*?~~~)/gi;
790
- const tokens = [];
791
- let lastIdx = 0;
792
- let m;
793
- while ((m = protectedBlockRe.exec(s)) !== null) {
794
- if (m.index > lastIdx) {
795
- tokens.push({ protected: false, text: s.slice(lastIdx, m.index) });
796
- }
797
- tokens.push({ protected: true, text: m[0] });
798
- lastIdx = m.index + m[0].length;
799
- }
800
- if (lastIdx < s.length) {
801
- tokens.push({ protected: false, text: s.slice(lastIdx) });
802
- }
803
- const segments = [];
804
- for (const t of tokens) {
805
- if (t.protected) {
806
- segments.push(t);
807
- } else {
808
- for (const part of t.text.split(/(\n\s*\n)/)) {
809
- if (!part) continue;
810
- segments.push({ protected: /^\n\s*\n$/.test(part), text: part });
811
- }
812
- }
813
- }
814
- return segments;
815
- }
816
-
817
- function resolvePreferredModelId(discoveredModels = [], cacheDir = null) {
818
- const installed = listInstalledModels(cacheDir).filter((m) => m.exists);
819
- for (const inst of installed) {
820
- if (discoveredModels.includes(inst.id)) return inst.id;
821
- const stem = inst.id.replace(/\.(?:gguf|bin|onnx)$/i, "").toLowerCase();
822
- const hit = discoveredModels.find((dm) => dm.toLowerCase().includes(stem));
823
- if (hit) return hit;
824
- }
825
- if (discoveredModels.length > 0) return discoveredModels[0];
826
- if (installed.length > 0) return installed[0].id;
827
- return "qwen3:1.7b";
828
- }
829
-
830
- export async function runLocalDeslop({
831
- text,
832
- pack,
833
- modality = "markdown",
834
- register = null,
835
- endpoint = null,
836
- runnerKind = null,
837
- model = null,
838
- allowLan = false,
839
- timeoutMs = 30000,
840
- cacheDir = null,
841
- } = {}) {
842
- let resolvedEndpoint = endpoint || process.env.DISLOP_LOCAL_URL || null;
843
- let resolvedKind = runnerKind || null;
844
- let resolvedModel = model || process.env.DISLOP_LOCAL_MODEL || null;
845
-
846
- if (!resolvedEndpoint) {
847
- const discovered = await discoverLocalRunners({ timeoutMs: 400 });
848
- if (discovered.length === 0) {
849
- return {
850
- ok: false,
851
- error:
852
- "No active local model daemon found on 127.0.0.1:11434 (Ollama) or 127.0.0.1:8080 (llama-server). Run 'dislop model status' or 'dislop model install'.",
853
- };
854
- }
855
- resolvedEndpoint = discovered[0].endpoint;
856
- resolvedKind = discovered[0].kind;
857
- if (!resolvedModel) {
858
- resolvedModel = resolvePreferredModelId(discovered[0].models || [], cacheDir);
859
- }
860
- } else {
861
- if (!resolvedKind) {
862
- resolvedKind = resolvedEndpoint.includes(":11434") ? "ollama" : "openai-compatible-local";
863
- }
864
- if (!resolvedModel) {
865
- resolvedModel = resolvePreferredModelId([], cacheDir);
866
- }
867
- }
868
-
869
- assertSafeLocalEndpoint(resolvedEndpoint, { allowLan });
870
-
871
- const raw = String(text || "");
872
- const segments = splitDocumentPreservingProtectedBlocks(raw);
873
- const outSegments = [];
874
- const paragraphAudits = [];
875
- let rewrittenCount = 0;
876
- let fallbackCount = 0;
877
-
878
- for (const item of segments) {
879
- const seg = item.text;
880
- const trimmed = seg.trim();
881
- if (
882
- item.protected ||
883
- !trimmed ||
884
- trimmed.startsWith("#") ||
885
- trimmed.startsWith("|") ||
886
- trimmed.startsWith("<!--")
887
- ) {
888
- outSegments.push(seg);
889
- continue;
890
- }
891
-
892
- const beforeAudit = auditText(seg, { filename: "draft.md", modality, pack, register });
893
- const beforePocket = scorePocketSpan(seg);
894
- const needsRewrite = beforeAudit.findings.length > 0 || (beforePocket.eligible && beforePocket.slopProbability >= 0.65);
895
-
896
- if (!needsRewrite) {
897
- outSegments.push(seg);
898
- continue;
899
- }
900
-
901
- const protectedFacts = extractProtectedFacts(seg, { modality });
902
- let accepted = null;
903
- let fallbackReason = null;
904
- let repairFeedback = null;
905
-
906
- for (let attempt = 0; attempt < 2; attempt += 1) {
907
- const { systemPrompt, userPrompt } = buildParagraphDeslopPrompt(
908
- seg,
909
- beforeAudit.findings,
910
- beforePocket,
911
- protectedFacts,
912
- repairFeedback,
913
- { packId: pack?.id || "business-brief", register: register || "unspecified" }
914
- );
915
- const candidate = await callLocalChatCompletion({
916
- endpoint: resolvedEndpoint,
917
- kind: resolvedKind,
918
- model: resolvedModel,
919
- systemPrompt,
920
- userPrompt,
921
- timeoutMs,
922
- allowLan,
923
- });
924
- if (!candidate) {
925
- fallbackReason = "empty-model-response";
926
- continue;
927
- }
928
-
929
- const factCheck = verifyFactsWithUnits(seg, candidate, { modality });
930
- const afterAudit = auditText(candidate, { filename: "draft.md", modality, pack, register });
931
- const hardErrorsAfter = afterAudit.findings.filter((f) => f.severity === "error" || f.severity === "warning");
932
- const hardErrorsBefore = beforeAudit.findings.filter((f) => f.severity === "error" || f.severity === "warning");
933
-
934
- if (factCheck.ok && hardErrorsAfter.length <= hardErrorsBefore.length && hardErrorsAfter.length === 0) {
935
- accepted = candidate;
936
- break;
937
- }
938
-
939
- const reasons = [];
940
- if (!factCheck.ok) {
941
- const ledger = factCheck.ledger;
942
- const missing = [
943
- ...(ledger.missing || []).map((f) => f.raw),
944
- ...(ledger.qualifierDropped || []).map((f) => f.before),
945
- ...(ledger.addedNumbers || []).map((f) => `+${f.raw}`),
946
- ...factCheck.unitMismatches.map((u) => `unit:${u}`),
947
- ];
948
- reasons.push(`Fact verification failed (${missing.join(", ")})`);
949
- }
950
- if (hardErrorsAfter.length > 0) {
951
- reasons.push(`Residual slop rules triggered (${hardErrorsAfter.map((f) => f.ruleId).join(", ")})`);
952
- }
953
- fallbackReason = reasons.join("; ");
954
- repairFeedback = fallbackReason;
955
- }
956
-
957
- if (accepted !== null) {
958
- outSegments.push(accepted);
959
- rewrittenCount += 1;
960
- paragraphAudits.push({
961
- status: "rewritten",
962
- beforeFindings: beforeAudit.findings.length,
963
- beforePocketProb: beforePocket.slopProbability,
964
- afterPocketProb: scorePocketSpan(accepted).slopProbability,
965
- });
966
- } else {
967
- outSegments.push(seg);
968
- fallbackCount += 1;
969
- paragraphAudits.push({
970
- status: "kept-original",
971
- keptOriginal: true,
972
- fallbackReason: fallbackReason || "verification-failed",
973
- });
974
- }
975
- }
976
-
977
- let finalText = outSegments.join("");
978
- let finalCheck = verifyFactsWithUnits(raw, finalText, { modality });
979
- if (!finalCheck.ok) {
980
- finalText = raw;
981
- fallbackCount += rewrittenCount;
982
- rewrittenCount = 0;
983
- finalCheck = verifyFactsWithUnits(raw, finalText, { modality });
984
- }
985
-
986
- return {
987
- ok: true,
988
- endpoint: resolvedEndpoint,
989
- runnerKind: resolvedKind,
990
- model: resolvedModel,
991
- rewrittenParagraphs: rewrittenCount,
992
- keptOriginalParagraphs: fallbackCount,
993
- factLedgerOk: finalCheck.ok,
994
- paragraphs: paragraphAudits,
995
- text: finalText,
996
- };
997
- }