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
@@ -0,0 +1,461 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { verifyBaselineFacts } from "../kernel/fact-gate.mjs";
7
+ import { patchDocumentOnDisk } from "../kernel/patcher.mjs";
8
+ import {
9
+ computeSummaryCounts,
10
+ getItemTierKey,
11
+ serializeCleanReportItem,
12
+ } from "../kernel/pipeline.mjs";
13
+
14
+ function defaultClipboardCopy(text, platform = process.platform) {
15
+ const candidates =
16
+ platform === "darwin"
17
+ ? [["pbcopy", []]]
18
+ : platform === "win32"
19
+ ? [["clip", []]]
20
+ : [
21
+ ["wl-copy", []],
22
+ ["xclip", ["-selection", "clipboard"]],
23
+ ["xsel", ["--clipboard", "--input"]],
24
+ ];
25
+
26
+ for (const [cmd, args] of candidates) {
27
+ try {
28
+ const res = spawnSync(cmd, args, { input: text, encoding: "utf8", stdio: ["pipe", "ignore", "ignore"] });
29
+ if (res.status === 0) return true;
30
+ } catch {
31
+ // try next candidate
32
+ }
33
+ }
34
+ return false;
35
+ }
36
+
37
+ function defaultLaunchEditor(initialText, { env = process.env, platform = process.platform } = {}) {
38
+ const editorCmd =
39
+ env.VISUAL || env.EDITOR || (platform === "win32" ? "notepad" : "vi");
40
+ const tmpFile = path.join(
41
+ os.tmpdir(),
42
+ `dislop-edit-${process.pid}-${crypto.randomBytes(4).toString("hex")}.md`,
43
+ );
44
+ fs.writeFileSync(tmpFile, initialText, "utf8");
45
+
46
+ try {
47
+ const parts = editorCmd.trim().split(/\s+/);
48
+ const bin = parts[0];
49
+ const args = [...parts.slice(1), tmpFile];
50
+ const res = spawnSync(bin, args, { stdio: "inherit" });
51
+ if (res.error || (res.status !== 0 && res.status !== null)) {
52
+ return null;
53
+ }
54
+ return fs.readFileSync(tmpFile, "utf8");
55
+ } finally {
56
+ if (fs.existsSync(tmpFile)) {
57
+ try {
58
+ fs.unlinkSync(tmpFile);
59
+ } catch {
60
+ // ignore cleanup failure
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ function createKeypressQueue(stdin) {
67
+ const queue = [];
68
+ let waiter = null;
69
+ let closed = false;
70
+
71
+ const pushChar = (ch) => {
72
+ if (waiter) {
73
+ const w = waiter;
74
+ waiter = null;
75
+ w(ch);
76
+ } else {
77
+ queue.push(ch);
78
+ }
79
+ };
80
+
81
+ const onData = (chunk) => {
82
+ const str = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
83
+ for (const ch of str) {
84
+ if (ch === "\u0003") {
85
+ // Ctrl+C -> treat as quit without applying further
86
+ pushChar("\u0003");
87
+ continue;
88
+ }
89
+ if (ch === "\r" || ch === "\n" || ch === " " || ch === "\t") continue;
90
+ pushChar(ch);
91
+ }
92
+ };
93
+
94
+ const onEnd = () => {
95
+ closed = true;
96
+ if (waiter) {
97
+ const w = waiter;
98
+ waiter = null;
99
+ w("q");
100
+ }
101
+ };
102
+
103
+ const wasRaw = Boolean(stdin.isRaw);
104
+ if (typeof stdin.setRawMode === "function" && stdin.isTTY) {
105
+ stdin.setRawMode(true);
106
+ }
107
+ if (typeof stdin.resume === "function") {
108
+ stdin.resume();
109
+ }
110
+ stdin.on("data", onData);
111
+ stdin.on("end", onEnd);
112
+
113
+ return {
114
+ async nextKey() {
115
+ if (queue.length > 0) return queue.shift();
116
+ if (closed) return "q";
117
+ return new Promise((resolve) => {
118
+ waiter = resolve;
119
+ });
120
+ },
121
+ dispose() {
122
+ stdin.off("data", onData);
123
+ stdin.off("end", onEnd);
124
+ if (typeof stdin.setRawMode === "function" && stdin.isTTY) {
125
+ stdin.setRawMode(wasRaw);
126
+ }
127
+ if (typeof stdin.pause === "function") {
128
+ stdin.pause();
129
+ }
130
+ },
131
+ };
132
+ }
133
+
134
+ function renderHunkBanner(item, index, total) {
135
+ const kindLabel = item.kind.toUpperCase();
136
+ const levelLabel = (item.kind === "defect" ? item.severity : item.priority).toUpperCase();
137
+ const coordParts = [item.targetId, item.line ? `L${item.line}` : null].filter(Boolean).join(" | ");
138
+ const coordDisplay = coordParts ? ` (${coordParts})` : "";
139
+
140
+ const lines = [
141
+ `\n── [${index + 1}/${total}] [${kindLabel} · ${levelLabel} · ${item.fixSafety}] ${item.ruleId}${coordDisplay} ──`,
142
+ `Reason: ${item.reason}`,
143
+ ];
144
+ if (item.verificationNote) {
145
+ lines.push(`Note : ${item.verificationNote}`);
146
+ }
147
+ lines.push("");
148
+ lines.push(`- ${item.originalQuote}`);
149
+ if (item.actionType === "delete" && item.fixSafety !== "manual") {
150
+ lines.push("+ (Delete sentence)");
151
+ } else if (item.suggestedReplacement) {
152
+ lines.push(`+ ${item.suggestedReplacement}`);
153
+ } else if (item.rewritePrompt) {
154
+ lines.push(`? Prompt: ${item.rewritePrompt}`);
155
+ } else {
156
+ lines.push("? (Manual edit required)");
157
+ }
158
+ lines.push("");
159
+ lines.push(
160
+ "Action: [y] accept [n] skip [e] edit ($EDITOR) [p] copy rewrite prompt",
161
+ );
162
+ lines.push(
163
+ "Batch : [a] accept remaining safe in tier [A] accept all safe/review [s] skip tier [u] undo [q] save & quit > ",
164
+ );
165
+ return lines.join("\n");
166
+ }
167
+
168
+ function canAutoAcceptItem(item) {
169
+ if (item.fixSafety === "manual") return false;
170
+ if (item.actionType === "delete") return Boolean(item.targetId || item._locator);
171
+ if (item.actionType === "replace") {
172
+ return Boolean(item.suggestedReplacement !== "" && (item.targetId || item._locator));
173
+ }
174
+ return false;
175
+ }
176
+
177
+ /**
178
+ * Interactive TTY Hunk State Machine (`y/n/e/p/a/A/s/u/q`).
179
+ */
180
+ export async function runInteractiveTtySession(
181
+ docResult,
182
+ {
183
+ stdin = process.stdin,
184
+ stdout = process.stdout,
185
+ env = process.env,
186
+ dryRun = false,
187
+ backup = false,
188
+ keyReader = null,
189
+ editorRunner = null,
190
+ clipboardRunner = null,
191
+ } = {},
192
+ ) {
193
+ const { doc, items, report } = docResult;
194
+ if (items.length === 0) {
195
+ stdout.write(`${report.file}: clean (0 items)\n`);
196
+ return { appliedCount: 0, modified: false, diff: "", report };
197
+ }
198
+
199
+ let reader = keyReader || createKeypressQueue(stdin);
200
+ const ownedReader = !keyReader;
201
+
202
+ // Map itemIndex -> decision `{ status: 'accepted' | 'skipped' | 'edited', patch?: Object }`
203
+ let decisions = new Map();
204
+ const undoStack = [];
205
+ let idx = 0;
206
+
207
+ const snapshotState = () => {
208
+ undoStack.push({
209
+ idx,
210
+ decisions: new Map(decisions),
211
+ });
212
+ };
213
+
214
+ try {
215
+ while (idx < items.length) {
216
+ const item = items[idx];
217
+ stdout.write(renderHunkBanner(item, idx, items.length));
218
+
219
+ const key = await reader.nextKey();
220
+ stdout.write(`${key === "\u0003" ? "^C" : key}\n`);
221
+
222
+ if (key === "\u0003") {
223
+ // Abort immediately without saving
224
+ return { appliedCount: 0, modified: false, diff: "", aborted: true, report };
225
+ }
226
+
227
+ if (key === "q") {
228
+ break;
229
+ }
230
+
231
+ if (key === "u") {
232
+ if (undoStack.length === 0) {
233
+ stdout.write(" (Already at the first hunk; nothing to undo.)\n");
234
+ } else {
235
+ const prev = undoStack.pop();
236
+ idx = prev.idx;
237
+ decisions = prev.decisions;
238
+ stdout.write(` (Reverted back to hunk ${idx + 1}.)\n`);
239
+ }
240
+ continue;
241
+ }
242
+
243
+ if (key === "y") {
244
+ if (!canAutoAcceptItem(item)) {
245
+ stdout.write(
246
+ " Cannot auto-accept a 'manual' item without a verified replacement. Press [e] to edit or [p] to copy prompt.\n",
247
+ );
248
+ continue;
249
+ }
250
+ snapshotState();
251
+ decisions.set(idx, {
252
+ status: "accepted",
253
+ patch: {
254
+ targetId: item.targetId,
255
+ locator: item._locator || null,
256
+ originalQuote: item.originalQuote,
257
+ replacement: item.actionType === "delete" ? "" : item.suggestedReplacement,
258
+ },
259
+ });
260
+ idx += 1;
261
+ continue;
262
+ }
263
+
264
+ if (key === "n") {
265
+ snapshotState();
266
+ decisions.set(idx, { status: "skipped" });
267
+ idx += 1;
268
+ continue;
269
+ }
270
+
271
+ if (key === "p") {
272
+ const promptText =
273
+ item.rewritePrompt ||
274
+ `Revise "${item.originalQuote}" — ${item.reason}`;
275
+ const copied = clipboardRunner
276
+ ? await clipboardRunner(promptText)
277
+ : defaultClipboardCopy(promptText);
278
+ if (copied) {
279
+ stdout.write(" Copied rewrite prompt to clipboard.\n");
280
+ } else {
281
+ stdout.write(` Rewrite prompt:\n ${promptText}\n`);
282
+ }
283
+ snapshotState();
284
+ decisions.set(idx, { status: "skipped" });
285
+ idx += 1;
286
+ continue;
287
+ }
288
+
289
+ if (key === "e") {
290
+ const seg = item.targetId ? doc.segments.find((s) => s.id === item.targetId) : null;
291
+ const para = seg
292
+ ? doc.paragraphs?.find((p) => p.id === seg.paragraphId)
293
+ : null;
294
+ const originalText = para ? para.text : item.originalQuote;
295
+ const editTargetId = para ? para.id : item.targetId;
296
+
297
+ if (!editTargetId && !item._locator) {
298
+ stdout.write(" This item has no editable text span locator.\n");
299
+ continue;
300
+ }
301
+
302
+ // Pause raw mode while spawning external interactive terminal editor, then resume cleanly
303
+ if (ownedReader) reader.dispose();
304
+ let editedRaw;
305
+ try {
306
+ editedRaw = editorRunner
307
+ ? await editorRunner(originalText, item)
308
+ : defaultLaunchEditor(originalText, { env });
309
+ } finally {
310
+ if (ownedReader) {
311
+ reader = createKeypressQueue(stdin);
312
+ }
313
+ }
314
+
315
+ if (editedRaw === null || editedRaw === undefined) {
316
+ stdout.write(" Editor cancelled; keeping hunk undecided.\n");
317
+ continue;
318
+ }
319
+
320
+ const trimmedEdited = String(editedRaw).replace(/\r?\n$/, "");
321
+ if (trimmedEdited === originalText) {
322
+ stdout.write(" No changes made in editor.\n");
323
+ continue;
324
+ }
325
+
326
+ const factRes = verifyBaselineFacts(originalText, trimmedEdited);
327
+ let keepManualEdit = true;
328
+ if (!factRes.ok) {
329
+ stdout.write(
330
+ ` Fact check notice: ${factRes.summary}. Keep manual edit anyway? [y/N] `,
331
+ );
332
+ const confirmKey = await reader.nextKey();
333
+ stdout.write(`${confirmKey}\n`);
334
+ keepManualEdit = confirmKey.toLowerCase() === "y";
335
+ }
336
+
337
+ if (!keepManualEdit) {
338
+ stdout.write(" Discarded manual edit.\n");
339
+ continue;
340
+ }
341
+
342
+ snapshotState();
343
+ decisions.set(idx, {
344
+ status: "edited",
345
+ patch: {
346
+ targetId: editTargetId,
347
+ locator: para ? para.locator : item._locator || null,
348
+ originalQuote: originalText,
349
+ replacement: trimmedEdited,
350
+ },
351
+ });
352
+ idx += 1;
353
+ continue;
354
+ }
355
+
356
+ if (key === "a") {
357
+ snapshotState();
358
+ const currentTier = getItemTierKey(item);
359
+ let cursor = idx;
360
+ while (cursor < items.length && getItemTierKey(items[cursor]) === currentTier) {
361
+ const curItem = items[cursor];
362
+ if (curItem.fixSafety === "safe" && canAutoAcceptItem(curItem)) {
363
+ decisions.set(cursor, {
364
+ status: "accepted",
365
+ patch: {
366
+ targetId: curItem.targetId,
367
+ locator: curItem._locator || null,
368
+ originalQuote: curItem.originalQuote,
369
+ replacement:
370
+ curItem.actionType === "delete" ? "" : curItem.suggestedReplacement,
371
+ },
372
+ });
373
+ } else {
374
+ decisions.set(cursor, { status: "skipped" });
375
+ }
376
+ cursor += 1;
377
+ }
378
+ idx = cursor;
379
+ continue;
380
+ }
381
+
382
+ if (key === "A") {
383
+ snapshotState();
384
+ for (let cursor = idx; cursor < items.length; cursor += 1) {
385
+ const curItem = items[cursor];
386
+ if (
387
+ (curItem.fixSafety === "safe" || curItem.fixSafety === "review") &&
388
+ canAutoAcceptItem(curItem)
389
+ ) {
390
+ decisions.set(cursor, {
391
+ status: "accepted",
392
+ patch: {
393
+ targetId: curItem.targetId,
394
+ locator: curItem._locator || null,
395
+ originalQuote: curItem.originalQuote,
396
+ replacement:
397
+ curItem.actionType === "delete" ? "" : curItem.suggestedReplacement,
398
+ },
399
+ });
400
+ } else {
401
+ decisions.set(cursor, { status: "skipped" });
402
+ }
403
+ }
404
+ idx = items.length;
405
+ continue;
406
+ }
407
+
408
+ if (key === "s") {
409
+ snapshotState();
410
+ const currentTier = getItemTierKey(item);
411
+ let cursor = idx;
412
+ while (cursor < items.length && getItemTierKey(items[cursor]) === currentTier) {
413
+ decisions.set(cursor, { status: "skipped" });
414
+ cursor += 1;
415
+ }
416
+ idx = cursor;
417
+ continue;
418
+ }
419
+
420
+ stdout.write(" Unknown key. Choose one of [y, n, e, p, a, A, s, u, q].\n");
421
+ }
422
+ } finally {
423
+ if (ownedReader) {
424
+ reader.dispose();
425
+ }
426
+ }
427
+
428
+ const patches = [];
429
+ const appliedIndices = new Set();
430
+ for (const [itemIdx, dec] of decisions.entries()) {
431
+ if ((dec.status === "accepted" || dec.status === "edited") && dec.patch) {
432
+ patches.push(dec.patch);
433
+ appliedIndices.add(itemIdx);
434
+ }
435
+ }
436
+
437
+ if (patches.length === 0) {
438
+ stdout.write("\nNo edits accepted; file left unchanged.\n");
439
+ return { appliedCount: 0, modified: false, diff: "", report };
440
+ }
441
+
442
+ const patchRes = patchDocumentOnDisk(doc, patches, { dryRun, backup });
443
+ if (patchRes.modified && !dryRun) {
444
+ for (const itemIdx of appliedIndices) {
445
+ items[itemIdx]._applied = true;
446
+ }
447
+ const remaining = items.filter((i) => !i._applied);
448
+ report.summary = computeSummaryCounts(remaining);
449
+ report.items = remaining.map(serializeCleanReportItem);
450
+ stdout.write(`\nSaved ${patches.length} change(s) to ${report.file}.\n`);
451
+ } else if (dryRun && patchRes.diff) {
452
+ stdout.write(`\n${patchRes.diff}\n`);
453
+ }
454
+
455
+ return {
456
+ appliedCount: patchRes.modified ? patches.length : 0,
457
+ modified: patchRes.modified,
458
+ diff: patchRes.diff,
459
+ report,
460
+ };
461
+ }
@@ -0,0 +1,256 @@
1
+ import fs from "node:fs";
2
+ import { formatDisplayCoordinate } from "../kernel/document-model.mjs";
3
+ import { applyPatchesToText, renderUnifiedDiff } from "../kernel/patcher.mjs";
4
+
5
+ /**
6
+ * Render `--format json` (`dislop.report/1` verbatim for single file; array of `dislop.report/1` for multi-file).
7
+ */
8
+ export function formatJsonReports(results) {
9
+ if (results.length === 1) {
10
+ return `${JSON.stringify(results[0].report, null, 2)}\n`;
11
+ }
12
+ return `${JSON.stringify(results.map((r) => r.report), null, 2)}\n`;
13
+ }
14
+
15
+ /**
16
+ * Render `--format agent`: token-compact structured feed for Coding & Writing Agents.
17
+ */
18
+ export function formatAgentReports(results) {
19
+ const blocks = [];
20
+
21
+ for (const { report } of results) {
22
+ const defectTotal = (report.summary.defects.error || 0) + (report.summary.defects.warning || 0);
23
+ const suggestionTotal =
24
+ (report.summary.suggestions.strong || 0) +
25
+ (report.summary.suggestions.moderate || 0) +
26
+ (report.summary.suggestions.hint || 0);
27
+
28
+ const lines = [
29
+ `# dislop file=${report.file} engine=${report.engine} defects=${defectTotal} suggestions=${suggestionTotal}`,
30
+ ];
31
+
32
+ for (const item of report.items) {
33
+ const coord = formatDisplayCoordinate(item.targetId, item.line);
34
+ const headerKind =
35
+ item.kind === "defect"
36
+ ? `DEFECT(${item.severity},${item.fixSafety})`
37
+ : `SUGGESTION(${item.priority},${item.fixSafety})`;
38
+ lines.push(`${coord} ${headerKind} ${item.ruleId}`);
39
+ lines.push(` quote: ${JSON.stringify(item.originalQuote)}`);
40
+ lines.push(` reason: ${item.reason}`);
41
+
42
+ if (item.actionType === "delete" && item.fixSafety !== "manual") {
43
+ lines.push(" fix: DELETE");
44
+ } else if (item.suggestedReplacement) {
45
+ lines.push(` fix: ${JSON.stringify(item.suggestedReplacement)}`);
46
+ } else if (item.rewritePrompt) {
47
+ lines.push(` prompt: ${item.rewritePrompt}`);
48
+ }
49
+ if (item.verificationNote) {
50
+ lines.push(` note: ${item.verificationNote}`);
51
+ }
52
+ }
53
+
54
+ blocks.push(lines.join("\n"));
55
+ }
56
+
57
+ return `${blocks.join("\n\n")}\n`;
58
+ }
59
+
60
+ /**
61
+ * Render `--format sarif` (SARIF 2.1.0).
62
+ * Maps `Suggestion` items strictly to `"note"` so IDE/GitHub integrations NEVER display red errors for prose.
63
+ */
64
+ export function formatSarifReports(results) {
65
+ const rulesMap = new Map();
66
+ const sarifResults = [];
67
+
68
+ for (const { report } of results) {
69
+ for (const item of report.items) {
70
+ if (!rulesMap.has(item.ruleId)) {
71
+ rulesMap.set(item.ruleId, {
72
+ id: item.ruleId,
73
+ shortDescription: { text: item.reason },
74
+ });
75
+ }
76
+
77
+ const level =
78
+ item.kind === "defect"
79
+ ? item.severity === "error"
80
+ ? "error"
81
+ : "warning"
82
+ : "note";
83
+
84
+ sarifResults.push({
85
+ ruleId: item.ruleId,
86
+ level,
87
+ message: {
88
+ text: item.rewritePrompt ? `${item.reason} (${item.rewritePrompt})` : item.reason,
89
+ },
90
+ locations: [
91
+ {
92
+ physicalLocation: {
93
+ artifactLocation: { uri: report.file },
94
+ region: {
95
+ startLine: item.line || 1,
96
+ snippet: { text: item.originalQuote },
97
+ },
98
+ },
99
+ },
100
+ ],
101
+ });
102
+ }
103
+ }
104
+
105
+ const sarif = {
106
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
107
+ version: "2.1.0",
108
+ runs: [
109
+ {
110
+ tool: {
111
+ driver: {
112
+ name: "dislop",
113
+ version: "1.0.1",
114
+ informationUri: "https://dislop.com",
115
+ rules: Array.from(rulesMap.values()),
116
+ },
117
+ },
118
+ results: sarifResults,
119
+ },
120
+ ],
121
+ };
122
+
123
+ return `${JSON.stringify(sarif, null, 2)}\n`;
124
+ }
125
+
126
+ /**
127
+ * Render `--format diff`: preview unified diff for all `safe` / `review` items without modifying disk.
128
+ */
129
+ export function formatDiffReports(results) {
130
+ const chunks = [];
131
+ for (const { doc, items, report } of results) {
132
+ const patchable = items.filter(
133
+ (i) =>
134
+ i.fixSafety !== "manual" &&
135
+ (i.actionType === "delete" || (i.actionType === "replace" && i.suggestedReplacement !== "")),
136
+ );
137
+ if (patchable.length === 0) continue;
138
+
139
+ if (doc.format === "docx" || doc.format === "pptx") {
140
+ for (const p of patchable) {
141
+ chunks.push(
142
+ `--- a/${report.file} [${p.targetId}]\n+++ b/${report.file} [${p.targetId}]\n-${p.originalQuote}\n+${p.actionType === "delete" ? "" : p.suggestedReplacement}`,
143
+ );
144
+ }
145
+ continue;
146
+ }
147
+
148
+ if (!fs.existsSync(doc.filePath)) continue;
149
+ const orig = fs.readFileSync(doc.filePath, "utf8");
150
+ const next = applyPatchesToText(
151
+ orig,
152
+ doc,
153
+ patchable.map((i) => ({
154
+ targetId: i.targetId,
155
+ locator: i._locator || null,
156
+ originalQuote: i.originalQuote,
157
+ replacement: i.actionType === "delete" ? "" : i.suggestedReplacement,
158
+ })),
159
+ );
160
+ const diff = renderUnifiedDiff(report.file, orig, next);
161
+ if (diff) chunks.push(diff);
162
+ }
163
+
164
+ return chunks.length > 0 ? `${chunks.join("\n\n")}\n` : "";
165
+ }
166
+
167
+ /**
168
+ * Render `--format text`: Dual-Track human-readable terminal report.
169
+ */
170
+ export function formatTextReports(results, { lang = "en" } = {}) {
171
+ const sections = [];
172
+
173
+ for (const { report } of results) {
174
+ const defects = report.items.filter((i) => i.kind === "defect");
175
+ const suggestions = report.items.filter((i) => i.kind === "suggestion");
176
+
177
+ const lines = [
178
+ `${report.file} (engine: ${report.engine}, packs: ${report.mountedPacks.join(", ")})`,
179
+ ];
180
+
181
+ if (report.documentToneAnchor) {
182
+ lines.push(` Tone: ${report.documentToneAnchor}`);
183
+ }
184
+
185
+ if (defects.length === 0 && suggestions.length === 0) {
186
+ lines.push(
187
+ lang === "zh"
188
+ ? " \u672a\u53d1\u73b0\u5df2\u77e5\u786c\u4f24\u6216\u53bb\u5473\u5efa\u8bae\u3002"
189
+ : " No artifact defects or editorial suggestions found.",
190
+ );
191
+ sections.push(lines.join("\n"));
192
+ continue;
193
+ }
194
+
195
+ if (defects.length > 0) {
196
+ lines.push(lang === "zh" ? "\n [\u4ea4\u4ed8\u786c\u4f24 DEFECTS]" : "\n [DEFECTS]");
197
+ for (const d of defects) {
198
+ const coord = formatDisplayCoordinate(d.targetId, d.line);
199
+ lines.push(` - ${d.severity.toUpperCase().padEnd(7)} ${coord} ${d.ruleId} (${d.fixSafety})`);
200
+ lines.push(` Quote : "${d.originalQuote}"`);
201
+ lines.push(` Reason: ${d.reason}`);
202
+ if (d.actionType === "delete" && d.fixSafety !== "manual") {
203
+ lines.push(" Fix : (Delete span)");
204
+ } else if (d.suggestedReplacement) {
205
+ lines.push(` Fix : "${d.suggestedReplacement}"`);
206
+ } else if (d.rewritePrompt) {
207
+ lines.push(` Action: ${d.rewritePrompt}`);
208
+ }
209
+ }
210
+ }
211
+
212
+ if (suggestions.length > 0) {
213
+ lines.push(
214
+ lang === "zh"
215
+ ? "\n [\u7f16\u8f91\u5efa\u8bae SUGGESTIONS \u2014 exit 0]"
216
+ : "\n [SUGGESTIONS — non-blocking, exit 0]",
217
+ );
218
+ for (const s of suggestions) {
219
+ const coord = formatDisplayCoordinate(s.targetId, s.line);
220
+ lines.push(` - ${s.priority.toUpperCase().padEnd(8)} ${coord} ${s.ruleId} (${s.fixSafety})`);
221
+ lines.push(` Quote : "${s.originalQuote}"`);
222
+ lines.push(` Reason: ${s.reason}`);
223
+ if (s.actionType === "delete" && s.fixSafety !== "manual") {
224
+ lines.push(" Fix : (Delete sentence)");
225
+ } else if (s.suggestedReplacement) {
226
+ lines.push(` Fix : "${s.suggestedReplacement}"`);
227
+ } else if (s.rewritePrompt) {
228
+ lines.push(` Prompt: ${s.rewritePrompt}`);
229
+ }
230
+ if (s.verificationNote) {
231
+ lines.push(` Gate : ${s.verificationNote}`);
232
+ }
233
+ }
234
+ }
235
+
236
+ sections.push(lines.join("\n"));
237
+ }
238
+
239
+ return `${sections.join("\n\n")}\n`;
240
+ }
241
+
242
+ export function renderReports(results, format = "text", { lang = "en" } = {}) {
243
+ switch (format) {
244
+ case "json":
245
+ return formatJsonReports(results);
246
+ case "agent":
247
+ return formatAgentReports(results);
248
+ case "sarif":
249
+ return formatSarifReports(results);
250
+ case "diff":
251
+ return formatDiffReports(results);
252
+ case "text":
253
+ default:
254
+ return formatTextReports(results, { lang });
255
+ }
256
+ }