dislop 0.9.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) 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 -63
  7. package/README.md +358 -249
  8. package/README.zh-CN.md +391 -237
  9. package/action.yml +30 -39
  10. package/bin/dislop-mcp.mjs +3 -4
  11. package/bin/dislop.mjs +4 -4594
  12. package/gemini-extension.json +2 -2
  13. package/llms-install.md +68 -0
  14. package/package.json +17 -63
  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 +235 -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 +293 -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 +2 -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/agents/openai.yaml +1 -1
  56. package/skills/dislop/references/essay.md +6 -6
  57. package/skills/dislop/references/essay.zh-CN.md +6 -6
  58. package/skills/dislop/references/office.md +5 -5
  59. package/skills/dislop/references/office.zh-CN.md +5 -5
  60. package/skills/dislop/references/web-ui.md +4 -4
  61. package/skills/dislop/references/web-ui.zh-CN.md +4 -4
  62. package/skills/dislop/references/work-docs.md +7 -7
  63. package/skills/dislop/references/work-docs.zh-CN.md +7 -7
  64. package/src/cli-main.mjs +292 -0
  65. package/src/commands/check-fix.mjs +324 -0
  66. package/src/commands/doctor.mjs +132 -0
  67. package/src/commands/init.mjs +55 -0
  68. package/src/commands/login.mjs +82 -0
  69. package/src/commands/model.mjs +130 -0
  70. package/src/commands/packs.mjs +81 -0
  71. package/src/commands/verify.mjs +165 -0
  72. package/src/commands/voice.mjs +84 -0
  73. package/src/commands/worklog.mjs +424 -0
  74. package/src/kernel/config.mjs +759 -0
  75. package/src/kernel/document-model.mjs +1432 -0
  76. package/src/kernel/fact-gate.mjs +775 -0
  77. package/src/kernel/file-discovery.mjs +296 -0
  78. package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +615 -890
  79. package/src/kernel/pack-loader.mjs +801 -0
  80. package/src/kernel/pack-validator.mjs +491 -0
  81. package/src/kernel/patcher.mjs +471 -0
  82. package/src/kernel/pipeline.mjs +530 -0
  83. package/src/kernel/prompt-assembler.mjs +336 -0
  84. package/src/kernel/version.mjs +7 -0
  85. package/src/kernel/voice-profile.mjs +180 -0
  86. package/src/mcp/stdio-server.mjs +442 -0
  87. package/src/runners/auto-fix.mjs +74 -0
  88. package/src/runners/interactive-tty.mjs +488 -0
  89. package/src/runners/reporters.mjs +272 -0
  90. package/src/runtime/chunker.mjs +87 -0
  91. package/src/runtime/json-extract.mjs +144 -0
  92. package/src/runtime/privacy-gate.mjs +97 -0
  93. package/src/runtime/providers/anthropic.mjs +65 -0
  94. package/src/runtime/providers/cloud.mjs +138 -0
  95. package/src/runtime/providers/gemini.mjs +91 -0
  96. package/src/runtime/providers/local-model.mjs +147 -0
  97. package/src/runtime/providers/openai-compat.mjs +130 -0
  98. package/src/runtime/router.mjs +324 -0
  99. package/src/runtime/worklog.mjs +904 -0
  100. package/src/sdk/index.mjs +137 -0
  101. package/models/manifest.json +0 -90
  102. package/models/pocket-slop-v1.json +0 -1
  103. package/packs/business-brief/pack.json +0 -937
  104. package/packs/core/pack.json +0 -209
  105. package/packs/deck-and-ui/pack.json +0 -539
  106. package/packs/engineering-spec/pack.json +0 -144
  107. package/packs/executive-deck/pack.json +0 -98
  108. package/packs/literary-essay/pack.json +0 -344
  109. package/packs/regulated-comms/pack.json +0 -99
  110. package/patterns/ai-tic-rubric.json +0 -252
  111. package/patterns/banks/composite-fusion.json +0 -48
  112. package/patterns/banks/discourse-rhythm.json +0 -95
  113. package/patterns/banks/lexical-signals.json +0 -92
  114. package/patterns/banks/syntactic-frames.json +0 -52
  115. package/patterns/banks/visual-deck.json +0 -44
  116. package/patterns/dimensions/artifacts.json +0 -121
  117. package/patterns/dimensions/discourse.json +0 -438
  118. package/patterns/dimensions/lexical.json +0 -198
  119. package/patterns/dimensions/rhythm.json +0 -258
  120. package/patterns/dimensions/syntactic.json +0 -285
  121. package/patterns/dimensions/visual-and-deck.json +0 -530
  122. package/patterns/taxonomy.json +0 -112
  123. package/src/core.mjs +0 -5497
  124. package/src/dislop/review-picker.vim +0 -114
  125. package/src/local-model.mjs +0 -997
  126. package/src/pattern-engine.mjs +0 -1003
  127. package/src/pocket-model.mjs +0 -729
  128. package/src/review-apply.mjs +0 -151
  129. package/src/review-client.mjs +0 -1073
@@ -0,0 +1,442 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+ import { resolveLayeredConfig } from "../kernel/config.mjs";
6
+ import { verifyDocumentRevision } from "../kernel/fact-gate.mjs";
7
+ import { listBuiltinPackIds } from "../kernel/pack-loader.mjs";
8
+ import { runDocumentPipeline } from "../kernel/pipeline.mjs";
9
+ import { DISLOP_VERSION } from "../kernel/version.mjs";
10
+ import { runAutoFixOnDocumentResult } from "../runners/auto-fix.mjs";
11
+ import { formatAgentReports } from "../runners/reporters.mjs";
12
+ import { resolveExecutionRoute } from "../runtime/router.mjs";
13
+ import {
14
+ buildCheckOrFixWorklogEntry,
15
+ buildVerifyWorklogEntry,
16
+ recordWorklogEntry,
17
+ } from "../runtime/worklog.mjs";
18
+
19
+ const SUPPORTED_MCP_VERSIONS = ["2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"];
20
+
21
+ export const LOCAL_MCP_TOOLS = [
22
+ {
23
+ name: "dislop_check",
24
+ description:
25
+ "Inspect a file or inline text for objective delivery Defects and non-blocking editorial Suggestions (returns compact agent report + dislop.report/1).",
26
+ annotations: {
27
+ readOnlyHint: true,
28
+ idempotentHint: true,
29
+ destructiveHint: false,
30
+ openWorldHint: false,
31
+ },
32
+ inputSchema: {
33
+ type: "object",
34
+ properties: {
35
+ filePath: { type: "string", description: "Path to local file on disk" },
36
+ text: { type: "string", description: "Inline document text when checking unsaved content" },
37
+ format: {
38
+ type: "string",
39
+ description: "Document format extension when passing inline text (e.g., md, html, jsx)",
40
+ },
41
+ packs: {
42
+ type: "array",
43
+ items: { type: "string" },
44
+ description: "Optional Pack IDs or paths (e.g., ['common/artifact-qa', 'en/prose'])",
45
+ },
46
+ noLlm: { type: "boolean", description: "Run deterministic Script Packs only (default true for fast local MCP checks)" },
47
+ level: { type: "string", enum: ["strong", "moderate", "hint", "all"] },
48
+ },
49
+ },
50
+ },
51
+ {
52
+ name: "dislop_fix_safe",
53
+ description:
54
+ "Atomically apply verified fixSafety === 'safe' edits on a local file and return the unified diff + remaining report.",
55
+ annotations: {
56
+ readOnlyHint: false,
57
+ idempotentHint: true,
58
+ destructiveHint: false,
59
+ openWorldHint: false,
60
+ },
61
+ inputSchema: {
62
+ type: "object",
63
+ required: ["filePath"],
64
+ properties: {
65
+ filePath: { type: "string" },
66
+ dryRun: { type: "boolean" },
67
+ backup: { type: "boolean" },
68
+ packs: { type: "array", items: { type: "string" } },
69
+ },
70
+ },
71
+ },
72
+ {
73
+ name: "dislop_verify",
74
+ description:
75
+ "Verify that a revised draft preserved all numbers, units, URLs, inline code spans, and proper nouns from the original without introducing second-order AI slogans.",
76
+ annotations: {
77
+ readOnlyHint: true,
78
+ idempotentHint: true,
79
+ destructiveHint: false,
80
+ openWorldHint: false,
81
+ },
82
+ inputSchema: {
83
+ type: "object",
84
+ required: ["beforeText", "afterText"],
85
+ properties: {
86
+ beforeText: { type: "string" },
87
+ afterText: { type: "string" },
88
+ },
89
+ },
90
+ },
91
+ {
92
+ name: "dislop_packs",
93
+ description: "List built-in multi-modal and language Packs available in this dislop installation.",
94
+ annotations: {
95
+ readOnlyHint: true,
96
+ idempotentHint: true,
97
+ destructiveHint: false,
98
+ openWorldHint: false,
99
+ },
100
+ inputSchema: {
101
+ type: "object",
102
+ properties: {},
103
+ },
104
+ },
105
+ ];
106
+
107
+ export async function handleMcpJsonRpcRequest(msg, { cwd = process.cwd(), env = process.env } = {}) {
108
+ if (!msg || typeof msg !== "object") {
109
+ return {
110
+ jsonrpc: "2.0",
111
+ id: null,
112
+ error: { code: -32600, message: "Invalid JSON-RPC request" },
113
+ };
114
+ }
115
+
116
+ // Notifications carry no `id` and produce no response frame
117
+ if (msg.id === undefined) {
118
+ return null;
119
+ }
120
+
121
+ const { id, method, params = {} } = msg;
122
+
123
+ try {
124
+ if (method === "initialize") {
125
+ const clientVer = params?.protocolVersion;
126
+ const protocolVersion = SUPPORTED_MCP_VERSIONS.includes(clientVer)
127
+ ? clientVer
128
+ : "2025-03-26";
129
+ return {
130
+ jsonrpc: "2.0",
131
+ id,
132
+ result: {
133
+ protocolVersion,
134
+ serverInfo: {
135
+ name: "dislop",
136
+ version: DISLOP_VERSION,
137
+ },
138
+ capabilities: {
139
+ tools: {},
140
+ },
141
+ instructions:
142
+ "Use dislop_check to audit deliverables (Defects vs. non-blocking Suggestions). After revising prose in project context, call dislop_verify to ensure no numbers, units, URLs, code spans, or entities were dropped.",
143
+ },
144
+ };
145
+ }
146
+
147
+ if (method === "ping") {
148
+ return { jsonrpc: "2.0", id, result: {} };
149
+ }
150
+
151
+ if (method === "tools/list") {
152
+ return {
153
+ jsonrpc: "2.0",
154
+ id,
155
+ result: { tools: LOCAL_MCP_TOOLS },
156
+ };
157
+ }
158
+
159
+ if (method === "tools/call") {
160
+ const toolName = params?.name;
161
+ const args = params?.arguments || {};
162
+
163
+ if (toolName === "dislop_packs") {
164
+ const packs = listBuiltinPackIds();
165
+ return {
166
+ jsonrpc: "2.0",
167
+ id,
168
+ result: {
169
+ content: [{ type: "text", text: JSON.stringify({ packs }, null, 2) }],
170
+ structuredContent: { packs },
171
+ },
172
+ };
173
+ }
174
+
175
+ if (toolName === "dislop_verify") {
176
+ const startedAt = Date.now();
177
+ const res = verifyDocumentRevision(String(args.beforeText || ""), String(args.afterText || ""));
178
+ try {
179
+ const cfg = resolveLayeredConfig({ cwd, env });
180
+ recordWorklogEntry(
181
+ buildVerifyWorklogEntry({
182
+ source: "mcp",
183
+ command: "verify",
184
+ mode: "mcp-verify",
185
+ cwd,
186
+ config: cfg,
187
+ targetLabel: "mcp-inline",
188
+ verification: res,
189
+ durationMs: Date.now() - startedAt,
190
+ exitCode: res.ok ? 0 : 1,
191
+ }),
192
+ cfg,
193
+ env,
194
+ );
195
+ } catch {
196
+ // Worklog recording must never break MCP tool calls
197
+ }
198
+ return {
199
+ jsonrpc: "2.0",
200
+ id,
201
+ result: {
202
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
203
+ structuredContent: res,
204
+ },
205
+ };
206
+ }
207
+
208
+ if (toolName === "dislop_check") {
209
+ const startedAt = Date.now();
210
+ let targetPath = args.filePath ? path.resolve(cwd, String(args.filePath)) : null;
211
+ let tmpFile = null;
212
+
213
+ try {
214
+ if (!targetPath) {
215
+ if (typeof args.text !== "string") {
216
+ throw new Error("Provide either 'filePath' or 'text' to dislop_check.");
217
+ }
218
+ const ext = String(args.format || "md").replace(/^\./, "");
219
+ tmpFile = path.join(
220
+ os.tmpdir(),
221
+ `dislop-mcp-${process.pid}-${crypto.randomBytes(4).toString("hex")}.${ext}`,
222
+ );
223
+ fs.writeFileSync(tmpFile, args.text, "utf8");
224
+ targetPath = tmpFile;
225
+ }
226
+
227
+ const config = resolveLayeredConfig({
228
+ cwd,
229
+ env,
230
+ cliFlags: {
231
+ packs: Array.isArray(args.packs) ? args.packs : null,
232
+ packOrigin: Array.isArray(args.packs) ? "mcp" : undefined,
233
+ noLlm: args.noLlm !== undefined ? Boolean(args.noLlm) : true,
234
+ level: args.level || "all",
235
+ },
236
+ });
237
+ const route = await resolveExecutionRoute({ config, isTty: false, env });
238
+ const docRes = await runDocumentPipeline({ filePath: targetPath, config, route, cwd });
239
+ if (tmpFile) {
240
+ docRes.report.file = `inline.${args.format || "md"}`;
241
+ }
242
+ const agentText = formatAgentReports([docRes]);
243
+ const exitCode = (docRes.report.summary?.defects?.error || 0) > 0 ? 1 : 0;
244
+ recordWorklogEntry(
245
+ buildCheckOrFixWorklogEntry({
246
+ source: "mcp",
247
+ command: "check",
248
+ mode: tmpFile ? "mcp-inline" : "mcp-file",
249
+ cwd,
250
+ config,
251
+ route,
252
+ results: [docRes],
253
+ durationMs: Date.now() - startedAt,
254
+ exitCode,
255
+ }),
256
+ config,
257
+ env,
258
+ );
259
+
260
+ return {
261
+ jsonrpc: "2.0",
262
+ id,
263
+ result: {
264
+ content: [{ type: "text", text: agentText }],
265
+ structuredContent: docRes.report,
266
+ },
267
+ };
268
+ } finally {
269
+ if (tmpFile && fs.existsSync(tmpFile)) {
270
+ fs.unlinkSync(tmpFile);
271
+ }
272
+ }
273
+ }
274
+
275
+ if (toolName === "dislop_fix_safe") {
276
+ if (!args.filePath) {
277
+ throw new Error("dislop_fix_safe requires 'filePath'.");
278
+ }
279
+ const startedAt = Date.now();
280
+ const targetPath = path.resolve(cwd, String(args.filePath));
281
+ const config = resolveLayeredConfig({
282
+ cwd,
283
+ env,
284
+ cliFlags: {
285
+ packs: Array.isArray(args.packs) ? args.packs : null,
286
+ packOrigin: Array.isArray(args.packs) ? "mcp" : undefined,
287
+ noLlm: true,
288
+ },
289
+ });
290
+ const route = await resolveExecutionRoute({ config, isTty: false, env });
291
+ const docRes = await runDocumentPipeline({ filePath: targetPath, config, route, cwd });
292
+ const fixRes = runAutoFixOnDocumentResult(docRes, {
293
+ dryRun: Boolean(args.dryRun),
294
+ backup: Boolean(args.backup),
295
+ });
296
+ const exitCode = (fixRes.report.summary?.defects?.error || 0) > 0 ? 1 : 0;
297
+ recordWorklogEntry(
298
+ buildCheckOrFixWorklogEntry({
299
+ source: "mcp",
300
+ command: "fix",
301
+ mode: args.dryRun ? "mcp-fix-dry-run" : "mcp-fix-auto",
302
+ cwd,
303
+ config,
304
+ route,
305
+ results: [docRes],
306
+ decisionsByFile: [
307
+ {
308
+ decisions: fixRes.decisions || {},
309
+ undoCount: 0,
310
+ aborted: false,
311
+ },
312
+ ],
313
+ durationMs: Date.now() - startedAt,
314
+ exitCode,
315
+ }),
316
+ config,
317
+ env,
318
+ );
319
+
320
+ return {
321
+ jsonrpc: "2.0",
322
+ id,
323
+ result: {
324
+ content: [
325
+ {
326
+ type: "text",
327
+ text: JSON.stringify(
328
+ {
329
+ appliedCount: fixRes.appliedCount,
330
+ modified: fixRes.modified,
331
+ diff: fixRes.diff,
332
+ report: fixRes.report,
333
+ },
334
+ null,
335
+ 2,
336
+ ),
337
+ },
338
+ ],
339
+ structuredContent: {
340
+ appliedCount: fixRes.appliedCount,
341
+ modified: fixRes.modified,
342
+ report: fixRes.report,
343
+ },
344
+ },
345
+ };
346
+ }
347
+
348
+ return {
349
+ jsonrpc: "2.0",
350
+ id,
351
+ error: { code: -32601, message: `Unknown tool '${toolName}'` },
352
+ };
353
+ }
354
+
355
+ return {
356
+ jsonrpc: "2.0",
357
+ id,
358
+ error: { code: -32601, message: `Method not found: '${method}'` },
359
+ };
360
+ } catch (err) {
361
+ return {
362
+ jsonrpc: "2.0",
363
+ id,
364
+ result: {
365
+ isError: true,
366
+ content: [{ type: "text", text: err.message }],
367
+ },
368
+ };
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Start the stdio JSON-RPC 2.0 MCP server loop (supports newline-delimited JSON-RPC and Content-Length framing).
374
+ */
375
+ export function startStdioMcpServer({
376
+ stdin = process.stdin,
377
+ stdout = process.stdout,
378
+ cwd = process.cwd(),
379
+ env = process.env,
380
+ } = {}) {
381
+ let buffer = Buffer.alloc(0);
382
+ let useContentLength = false;
383
+
384
+ const sendResponse = (resObj) => {
385
+ if (!resObj) return;
386
+ const json = JSON.stringify(resObj);
387
+ if (useContentLength) {
388
+ const byteLen = Buffer.byteLength(json, "utf8");
389
+ stdout.write(`Content-Length: ${byteLen}\r\n\r\n${json}`);
390
+ } else {
391
+ stdout.write(`${json}\n`);
392
+ }
393
+ };
394
+
395
+ const drainBuffer = async () => {
396
+ while (buffer.length > 0) {
397
+ const asciiHead = buffer.subarray(0, Math.min(buffer.length, 32)).toString("utf8");
398
+ if (/^Content-Length:/i.test(asciiHead)) {
399
+ useContentLength = true;
400
+ const headerEnd = buffer.indexOf("\r\n\r\n");
401
+ if (headerEnd === -1) return;
402
+ const headerStr = buffer.subarray(0, headerEnd).toString("utf8");
403
+ const lenMatch = headerStr.match(/Content-Length:\s*(\d+)/i);
404
+ if (!lenMatch) {
405
+ buffer = buffer.subarray(headerEnd + 4);
406
+ continue;
407
+ }
408
+ const bodyLen = parseInt(lenMatch[1], 10);
409
+ const frameEnd = headerEnd + 4 + bodyLen;
410
+ if (buffer.length < frameEnd) return;
411
+ const bodyStr = buffer.subarray(headerEnd + 4, frameEnd).toString("utf8");
412
+ buffer = buffer.subarray(frameEnd);
413
+ try {
414
+ const parsed = JSON.parse(bodyStr);
415
+ const reply = await handleMcpJsonRpcRequest(parsed, { cwd, env });
416
+ sendResponse(reply);
417
+ } catch {
418
+ sendResponse({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
419
+ }
420
+ } else {
421
+ const nl = buffer.indexOf(0x0a);
422
+ if (nl === -1) return;
423
+ const line = buffer.subarray(0, nl).toString("utf8").trim();
424
+ buffer = buffer.subarray(nl + 1);
425
+ if (!line) continue;
426
+ try {
427
+ const parsed = JSON.parse(line);
428
+ const reply = await handleMcpJsonRpcRequest(parsed, { cwd, env });
429
+ sendResponse(reply);
430
+ } catch {
431
+ sendResponse({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
432
+ }
433
+ }
434
+ }
435
+ };
436
+
437
+ stdin.on("data", (chunk) => {
438
+ const bufChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
439
+ buffer = Buffer.concat([buffer, bufChunk]);
440
+ drainBuffer();
441
+ });
442
+ }
@@ -0,0 +1,74 @@
1
+ import { computeSummaryCounts, serializeCleanReportItem } from "../kernel/pipeline.mjs";
2
+ import { patchDocumentOnDisk } from "../kernel/patcher.mjs";
3
+
4
+ /**
5
+ * Batch Auto-Fix runner (`dislop fix --auto`):
6
+ * Automatically applies ONLY verified `fixSafety === "safe"` items (`replace` or `delete`),
7
+ * updating `report.summary` and `report.items` to reflect remaining unresolved findings.
8
+ */
9
+ export function runAutoFixOnDocumentResult(docResult, { dryRun = false, backup = false } = {}) {
10
+ const { doc, items, report } = docResult;
11
+
12
+ const safeItems = items.filter(
13
+ (item) =>
14
+ item.fixSafety === "safe" &&
15
+ (item.actionType === "delete" ||
16
+ (item.actionType === "replace" && item.suggestedReplacement !== "")),
17
+ );
18
+
19
+ const decisions = {};
20
+ if (safeItems.length === 0) {
21
+ return {
22
+ appliedCount: 0,
23
+ modified: false,
24
+ diff: "",
25
+ decisions,
26
+ report,
27
+ };
28
+ }
29
+
30
+ const patches = safeItems.map((item) => ({
31
+ targetId: item.targetId,
32
+ locator: item._locator || null,
33
+ originalQuote: item.originalQuote,
34
+ replacement: item.actionType === "delete" ? "" : item.suggestedReplacement,
35
+ }));
36
+
37
+ const patchRes = patchDocumentOnDisk(doc, patches, {
38
+ dryRun,
39
+ backup,
40
+ displayPath: report.file,
41
+ });
42
+
43
+ let appliedCount = 0;
44
+ if (patchRes.modified && !dryRun) {
45
+ const appliedIdxSet =
46
+ patchRes.appliedIndices instanceof Set
47
+ ? patchRes.appliedIndices
48
+ : new Set(safeItems.map((_, idx) => idx));
49
+ const appliedIds = new Set();
50
+ safeItems.forEach((item, idx) => {
51
+ if (appliedIdxSet.has(idx)) {
52
+ appliedIds.add(item.id);
53
+ }
54
+ });
55
+ for (const item of items) {
56
+ if (appliedIds.has(item.id)) {
57
+ item._applied = true;
58
+ decisions[item.id] = "auto_applied";
59
+ appliedCount += 1;
60
+ }
61
+ }
62
+ const remaining = items.filter((i) => !i._applied);
63
+ report.summary = computeSummaryCounts(remaining);
64
+ report.items = remaining.map(serializeCleanReportItem);
65
+ }
66
+
67
+ return {
68
+ appliedCount,
69
+ modified: patchRes.modified,
70
+ diff: patchRes.diff,
71
+ decisions,
72
+ report,
73
+ };
74
+ }