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,471 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { decodeXmlEntities } from "./document-model.mjs";
5
+ import { readZipArchive, repackZipArchive } from "./ooxml-binary.mjs";
6
+
7
+ export function escapeXmlText(str) {
8
+ return String(str || "")
9
+ .replace(/&/g, "&")
10
+ .replace(/</g, "&lt;")
11
+ .replace(/>/g, "&gt;");
12
+ }
13
+
14
+ function detectEol(text) {
15
+ return text.includes("\r\n") ? "\r\n" : "\n";
16
+ }
17
+
18
+ /**
19
+ * Expand a deleted `[start, end]` span slightly to consume orphaned adjacent single space
20
+ * or empty list/heading lines so sentence deletion leaves clean typography.
21
+ */
22
+ function adjustTextSpanForDeletion(source, start, end) {
23
+ let s = start;
24
+ let e = end;
25
+
26
+ // Check if deleting this span leaves the rest of the line empty (or an empty list marker like `- `)
27
+ let lineStart = source.lastIndexOf("\n", s - 1);
28
+ lineStart = lineStart === -1 ? 0 : lineStart + 1;
29
+ let lineEnd = source.indexOf("\n", e);
30
+ const rawLineEnd = lineEnd === -1 ? source.length : lineEnd + 1;
31
+ if (lineEnd === -1) lineEnd = source.length;
32
+ const contentLineEnd = lineEnd > lineStart && source[lineEnd - 1] === "\r" ? lineEnd - 1 : lineEnd;
33
+
34
+ const prefix = source.slice(lineStart, s);
35
+ const suffix = source.slice(e, contentLineEnd);
36
+
37
+ if (/^\s*(?:(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?|>\s+|#{1,6}\s+)?$/.test(prefix) && /^\s*$/.test(suffix)) {
38
+ return { start: lineStart, end: rawLineEnd };
39
+ }
40
+
41
+ // Mid-line sentence deletion: eat trailing horizontal whitespace first, otherwise leading horizontal whitespace
42
+ if (e < contentLineEnd && /[ \t]/.test(source[e])) {
43
+ while (e < contentLineEnd && /[ \t]/.test(source[e])) e += 1;
44
+ } else if (s > lineStart && /[ \t]/.test(source[s - 1])) {
45
+ while (s > lineStart && /[ \t]/.test(source[s - 1])) s -= 1;
46
+ }
47
+
48
+ return { start: s, end: e };
49
+ }
50
+
51
+ function normalizePostPatchWhitespace(patched, eol, { hadLeadingNewline = false } = {}) {
52
+ const lf = patched.replace(/\r\n/g, "\n");
53
+ let cleaned = lf
54
+ // Strip orphaned leading comma/semicolon after sentence/clause deletion on a line
55
+ .replace(/(^|\n)([ \t]*)[,;:,;:]+[ \t]*/g, "$1$2")
56
+ // Collapse 3+ consecutive blank lines into a single blank line (2 newlines)
57
+ .replace(/\n{3,}/g, "\n\n");
58
+ if (!hadLeadingNewline) {
59
+ cleaned = cleaned.replace(/^\n+/, "");
60
+ }
61
+ return eol === "\r\n" ? cleaned.replace(/\n/g, "\r\n") : cleaned;
62
+ }
63
+
64
+ function resolveLocatorForPatch(doc, patch) {
65
+ if (patch.locator) return patch.locator;
66
+ if (!patch.targetId) return null;
67
+ const seg = doc.segments.find((s) => s.id === patch.targetId);
68
+ if (seg?.locator) {
69
+ if (patch.originalQuote && patch.originalQuote !== seg.text) {
70
+ const idx = seg.text.indexOf(patch.originalQuote);
71
+ if (idx === -1 || seg.text.indexOf(patch.originalQuote, idx + 1) !== -1) {
72
+ return null;
73
+ }
74
+ if (seg.locator.kind === "ooxml-span") {
75
+ return {
76
+ ...seg.locator,
77
+ charStart: seg.locator.charStart + idx,
78
+ charEnd: seg.locator.charStart + idx + patch.originalQuote.length,
79
+ };
80
+ }
81
+ return {
82
+ ...seg.locator,
83
+ start: seg.locator.start + idx,
84
+ end: seg.locator.start + idx + patch.originalQuote.length,
85
+ };
86
+ }
87
+ return seg.locator;
88
+ }
89
+ const para = doc.paragraphs?.find((p) => p.id === patch.targetId);
90
+ return para?.locator || null;
91
+ }
92
+
93
+ /**
94
+ * Apply accepted patches to an in-memory UTF-8 text/markup document string,
95
+ * returning both the patched text and exact set of applied patch indices.
96
+ */
97
+ export function applyPatchesToTextDetailed(sourceText, doc, patches) {
98
+ const appliedIndices = new Set();
99
+ if (!patches || patches.length === 0) return { text: sourceText, appliedIndices };
100
+ const eol = detectEol(sourceText);
101
+
102
+ const resolved = [];
103
+ for (let patchIdx = 0; patchIdx < patches.length; patchIdx += 1) {
104
+ const patch = patches[patchIdx];
105
+ const loc = resolveLocatorForPatch(doc, patch);
106
+ if (!loc || (loc.kind !== "text-span" && loc.kind !== "html-span")) continue;
107
+ let replacement = String(patch.replacement ?? "");
108
+ let span =
109
+ replacement === "" && loc.kind === "text-span"
110
+ ? adjustTextSpanForDeletion(sourceText, loc.start, loc.end)
111
+ : { start: loc.start, end: loc.end };
112
+ if (replacement !== "" && loc.kind === "text-span") {
113
+ const orig = sourceText.slice(span.start, span.end);
114
+ const minLen = Math.min(orig.length, replacement.length);
115
+ let cp = 0;
116
+ while (cp < minLen && orig[cp] === replacement[cp]) cp += 1;
117
+ let cs = 0;
118
+ while (cs < minLen - cp && orig[orig.length - 1 - cs] === replacement[replacement.length - 1 - cs]) cs += 1;
119
+ if (cp > 0 || cs > 0) {
120
+ span = { start: span.start + cp, end: span.end - cs };
121
+ replacement = replacement.slice(cp, replacement.length - cs);
122
+ }
123
+ }
124
+ resolved.push({
125
+ patchIdx,
126
+ start: span.start,
127
+ end: span.end,
128
+ replacement,
129
+ });
130
+ }
131
+
132
+ if (resolved.length === 0) return { text: sourceText, appliedIndices };
133
+
134
+ resolved.sort((a, b) => b.start - a.start || b.end - a.end);
135
+
136
+ let out = sourceText;
137
+ let minAppliedStart = Infinity;
138
+ for (const edit of resolved) {
139
+ if (edit.end > minAppliedStart) continue; // overlap guard
140
+ const beforeSlice = out.slice(edit.start, edit.end);
141
+ if (beforeSlice === edit.replacement) continue;
142
+ out = out.slice(0, edit.start) + edit.replacement + out.slice(edit.end);
143
+ minAppliedStart = edit.start;
144
+ appliedIndices.add(edit.patchIdx);
145
+ }
146
+
147
+ const finalText = normalizePostPatchWhitespace(out, eol, {
148
+ hadLeadingNewline: /^\r?\n/.test(sourceText),
149
+ });
150
+ return { text: finalText, appliedIndices };
151
+ }
152
+
153
+ /**
154
+ * Apply accepted patches (`Array<{ targetId?, locator?, originalQuote?, replacement: string }>`)
155
+ * to an in-memory UTF-8 text/markup document string.
156
+ */
157
+ export function applyPatchesToText(sourceText, doc, patches) {
158
+ return applyPatchesToTextDetailed(sourceText, doc, patches).text;
159
+ }
160
+
161
+ function patchSingleOoxmlParagraphXmlDetailed(pXml, nsPrefix, charEdits) {
162
+ const rTagRe = nsPrefix === "w" ? /<w:r\b[^>]*>[\s\S]*?<\/w:r>/g : /<a:r\b[^>]*>[\s\S]*?<\/a:r>/g;
163
+ const rPrTagRe = nsPrefix === "w" ? /<w:rPr\b[\s\S]*?<\/w:rPr>/ : /<a:rPr\b[\s\S]*?(?:\/>|<\/a:rPr>)/;
164
+ const tTagRe = nsPrefix === "w" ? /<w:t(?:\s+[^>]*)?>([\s\S]*?)<\/w:t>/g : /<a:t(?:\s+[^>]*)?>([\s\S]*?)<\/a:t>/g;
165
+
166
+ const hasProtectedNodes = /<(?:w:hyperlink|a:hlinkClick|w:fldSimple|w:instrText)\b/.test(pXml);
167
+ const runMatches = Array.from(pXml.matchAll(rTagRe));
168
+ const distinctRPr = new Set(
169
+ runMatches.map((rm) => {
170
+ const m = rm[0].match(rPrTagRe);
171
+ return m ? m[0] : "";
172
+ }),
173
+ );
174
+
175
+ // Locate each <w:t> / <a:t> slice in fullText and pXml
176
+ const tNodes = [];
177
+ let cursor = 0;
178
+ let tm;
179
+ while ((tm = tTagRe.exec(pXml)) !== null) {
180
+ const decoded = decodeXmlEntities(tm[1]);
181
+ const whole = tm[0];
182
+ const openEnd = whole.indexOf(">") + 1;
183
+ const closeStart = whole.lastIndexOf("</");
184
+ tNodes.push({
185
+ xmlStart: tm.index,
186
+ xmlEnd: tm.index + whole.length,
187
+ openTag: whole.slice(0, openEnd),
188
+ closeTag: whole.slice(closeStart),
189
+ textStart: cursor,
190
+ textEnd: cursor + decoded.length,
191
+ decoded,
192
+ });
193
+ cursor += decoded.length;
194
+ }
195
+
196
+ // If the paragraph holds hyperlinks, field codes, or mixed run styling, ONLY allow edits contained
197
+ // cleanly within a single <w:t>/<a:t> run (declining cross-run edits so formatting & links survive).
198
+ if (hasProtectedNodes || distinctRPr.size > 1) {
199
+ const sorted = [...charEdits].sort((a, b) => b.charStart - a.charStart);
200
+ const nodeTexts = tNodes.map((n) => n.decoded);
201
+ const appliedIndices = new Set();
202
+
203
+ for (const ed of sorted) {
204
+ const targetIdx = tNodes.findIndex((n) => ed.charStart >= n.textStart && ed.charEnd <= n.textEnd);
205
+ if (targetIdx === -1) continue;
206
+ const node = tNodes[targetIdx];
207
+ let s = ed.charStart - node.textStart;
208
+ let e = ed.charEnd - node.textStart;
209
+ let curStr = nodeTexts[targetIdx];
210
+ if (ed.replacement === "") {
211
+ if (e < curStr.length && curStr[e] === " ") e += 1;
212
+ else if (s > 0 && curStr[s - 1] === " ") s -= 1;
213
+ }
214
+ nodeTexts[targetIdx] = curStr.slice(0, s) + ed.replacement + curStr.slice(e);
215
+ if (ed.patchIndex !== undefined) appliedIndices.add(ed.patchIndex);
216
+ }
217
+
218
+ if (appliedIndices.size === 0) {
219
+ return { xml: pXml, appliedIndices };
220
+ }
221
+
222
+ let rebuilt = "";
223
+ let lastXml = 0;
224
+ for (let idx = 0; idx < tNodes.length; idx += 1) {
225
+ const node = tNodes[idx];
226
+ rebuilt += pXml.slice(lastXml, node.xmlStart);
227
+ const nextRaw = nodeTexts[idx];
228
+ const needsPreserve =
229
+ nsPrefix === "w" && (/^\s|\s$/.test(nextRaw) || /xml:space="preserve"/.test(node.openTag));
230
+ const openTag =
231
+ needsPreserve && !/xml:space=/.test(node.openTag)
232
+ ? node.openTag.replace(/^<w:t\b/, '<w:t xml:space="preserve"')
233
+ : node.openTag;
234
+ rebuilt += `${openTag}${escapeXmlText(nextRaw)}${node.closeTag}`;
235
+ lastXml = node.xmlEnd;
236
+ }
237
+ rebuilt += pXml.slice(lastXml);
238
+ return { xml: rebuilt, appliedIndices };
239
+ }
240
+
241
+ let firstRPr = "";
242
+ if (runMatches.length > 0) {
243
+ const rPrMatch = runMatches[0][0].match(rPrTagRe);
244
+ if (rPrMatch) firstRPr = rPrMatch[0];
245
+ }
246
+
247
+ let fullText = tNodes.map((n) => n.decoded).join("");
248
+ const appliedIndices = new Set();
249
+
250
+ // Apply edits in descending charStart order
251
+ const sorted = [...charEdits].sort((a, b) => b.charStart - a.charStart);
252
+ let minStart = Infinity;
253
+ for (const ed of sorted) {
254
+ if (ed.charEnd > minStart) continue;
255
+ let s = ed.charStart;
256
+ let e = ed.charEnd;
257
+ if (ed.replacement === "") {
258
+ if (e < fullText.length && fullText[e] === " ") e += 1;
259
+ else if (s > 0 && fullText[s - 1] === " ") s -= 1;
260
+ }
261
+ fullText = fullText.slice(0, s) + ed.replacement + fullText.slice(e);
262
+ minStart = s;
263
+ if (ed.patchIndex !== undefined) appliedIndices.add(ed.patchIndex);
264
+ }
265
+
266
+ const pPrRe = nsPrefix === "w" ? /<w:pPr\b[\s\S]*?<\/w:pPr>/ : /<a:pPr\b[\s\S]*?(?:\/>|<\/a:pPr>)/;
267
+ const openTagMatch = pXml.match(/^<(?:w|a):p\b[^>]*>/);
268
+ const openTag = openTagMatch ? openTagMatch[0] : `<${nsPrefix}:p>`;
269
+ const pPrMatch = pXml.match(pPrRe);
270
+ const pPr = pPrMatch ? pPrMatch[0] : "";
271
+
272
+ if (!fullText.trim()) {
273
+ return { xml: `${openTag}${pPr}</${nsPrefix}:p>`, appliedIndices };
274
+ }
275
+
276
+ const escaped = escapeXmlText(fullText);
277
+ if (nsPrefix === "w") {
278
+ return {
279
+ xml: `${openTag}${pPr}<w:r>${firstRPr}<w:t xml:space="preserve">${escaped}</w:t></w:r></w:p>`,
280
+ appliedIndices,
281
+ };
282
+ }
283
+ return {
284
+ xml: `${openTag}${pPr}<a:r>${firstRPr}<a:t>${escaped}</a:t></a:r></a:p>`,
285
+ appliedIndices,
286
+ };
287
+ }
288
+
289
+ /**
290
+ * Apply accepted patches to an OOXML (`.docx` / `.pptx`) archive buffer, returning a new Buffer.
291
+ */
292
+ export function applyPatchesToOoxmlBufferDetailed(originalBuffer, doc, patches) {
293
+ if (!patches || patches.length === 0) {
294
+ return { buffer: originalBuffer, appliedIndices: new Set() };
295
+ }
296
+ const { xmlEntries } = readZipArchive(originalBuffer);
297
+
298
+ // Group edits by entryName -> paragraphOrd
299
+ const byEntry = new Map();
300
+ for (let patchIdx = 0; patchIdx < patches.length; patchIdx += 1) {
301
+ const patch = patches[patchIdx];
302
+ const loc = resolveLocatorForPatch(doc, patch);
303
+ if (!loc || loc.kind !== "ooxml-span") continue;
304
+ let entryGroup = byEntry.get(loc.entryName);
305
+ if (!entryGroup) {
306
+ entryGroup = { nsPrefix: loc.nsPrefix, byPara: new Map() };
307
+ byEntry.set(loc.entryName, entryGroup);
308
+ }
309
+ let paraEdits = entryGroup.byPara.get(loc.paragraphOrd);
310
+ if (!paraEdits) {
311
+ paraEdits = [];
312
+ entryGroup.byPara.set(loc.paragraphOrd, paraEdits);
313
+ }
314
+ paraEdits.push({
315
+ charStart: loc.charStart,
316
+ charEnd: loc.charEnd,
317
+ replacement: String(patch.replacement ?? ""),
318
+ patchIndex: patchIdx,
319
+ });
320
+ }
321
+
322
+ if (byEntry.size === 0) {
323
+ return { buffer: originalBuffer, appliedIndices: new Set() };
324
+ }
325
+
326
+ const updatedXml = {};
327
+ const appliedIndices = new Set();
328
+ for (const [entryName, group] of byEntry.entries()) {
329
+ const xml = xmlEntries[entryName];
330
+ if (!xml) continue;
331
+ const pTagRe =
332
+ group.nsPrefix === "w" ? /<w:p\b[^>]*>[\s\S]*?<\/w:p>/g : /<a:p\b[^>]*>[\s\S]*?<\/a:p>/g;
333
+ let pOrd = 0;
334
+ updatedXml[entryName] = xml.replace(pTagRe, (pXml) => {
335
+ const idx = pOrd;
336
+ pOrd += 1;
337
+ const edits = group.byPara.get(idx);
338
+ if (!edits || edits.length === 0) return pXml;
339
+ const res = patchSingleOoxmlParagraphXmlDetailed(pXml, group.nsPrefix, edits);
340
+ if (res.xml !== pXml) {
341
+ for (const aIdx of res.appliedIndices) appliedIndices.add(aIdx);
342
+ }
343
+ return res.xml;
344
+ });
345
+ }
346
+
347
+ if (appliedIndices.size === 0) {
348
+ return { buffer: originalBuffer, appliedIndices };
349
+ }
350
+ return { buffer: repackZipArchive(originalBuffer, updatedXml), appliedIndices };
351
+ }
352
+
353
+ export function applyPatchesToOoxmlBuffer(originalBuffer, doc, patches) {
354
+ return applyPatchesToOoxmlBufferDetailed(originalBuffer, doc, patches).buffer;
355
+ }
356
+
357
+ /**
358
+ * Render a compact unified diff preview between `beforeText` and `afterText`.
359
+ */
360
+ export function renderUnifiedDiff(filePath, beforeText, afterText) {
361
+ if (beforeText === afterText) return "";
362
+ const aLines = beforeText.replace(/\r\n/g, "\n").split("\n");
363
+ const bLines = afterText.replace(/\r\n/g, "\n").split("\n");
364
+
365
+ const out = [`--- a/${filePath}`, `+++ b/${filePath}`];
366
+ const maxLen = Math.max(aLines.length, bLines.length);
367
+ let i = 0;
368
+ while (i < maxLen) {
369
+ if (aLines[i] === bLines[i]) {
370
+ i += 1;
371
+ continue;
372
+ }
373
+ const start = Math.max(0, i - 1);
374
+ let endA = i;
375
+ let endB = i;
376
+ while (endA < aLines.length || endB < bLines.length) {
377
+ if (endA < aLines.length && endB < bLines.length && aLines[endA] === bLines[endB]) break;
378
+ if (endA < aLines.length) endA += 1;
379
+ if (endB < bLines.length) endB += 1;
380
+ }
381
+ out.push(`@@ -${start + 1},${endA - start} +${start + 1},${endB - start} @@`);
382
+ if (start < i) out.push(` ${aLines[start]}`);
383
+ for (let k = i; k < endA; k += 1) {
384
+ if (aLines[k] !== undefined) out.push(`-${aLines[k]}`);
385
+ }
386
+ for (let k = i; k < endB; k += 1) {
387
+ if (bLines[k] !== undefined) out.push(`+${bLines[k]}`);
388
+ }
389
+ i = Math.max(endA, endB);
390
+ }
391
+ return out.join("\n");
392
+ }
393
+
394
+ /**
395
+ * Apply patches to `doc.filePath` (supporting `--dry-run` and `--backup` atomic temp-file rename).
396
+ */
397
+ export function patchDocumentOnDisk(doc, patches, { dryRun = false, backup = false, displayPath = null } = {}) {
398
+ if (!patches || patches.length === 0) {
399
+ return { modified: false, appliedIndices: new Set(), appliedCount: 0, diff: "" };
400
+ }
401
+
402
+ const filePath = doc.filePath;
403
+ const diffLabel = (displayPath || filePath).replace(/^\/+/, "");
404
+ if (doc.format === "docx" || doc.format === "pptx") {
405
+ const origBuf = fs.readFileSync(filePath);
406
+ const { buffer: nextBuf, appliedIndices } = applyPatchesToOoxmlBufferDetailed(origBuf, doc, patches);
407
+ if (origBuf.equals(nextBuf) || appliedIndices.size === 0) {
408
+ return { modified: false, appliedIndices: new Set(), appliedCount: 0, diff: "" };
409
+ }
410
+ const diffSummary = Array.from(appliedIndices)
411
+ .sort((a, b) => a - b)
412
+ .map((idx) => patches[idx])
413
+ .map(
414
+ (p) =>
415
+ `--- a/${diffLabel} [${p.targetId || "ooxml"}]\n+++ b/${diffLabel} [${p.targetId || "ooxml"}]\n-${p.originalQuote || ""}\n+${p.replacement || "(deleted)"}`,
416
+ )
417
+ .join("\n");
418
+ if (!dryRun) {
419
+ atomicWriteBuffer(filePath, nextBuf, { backup });
420
+ }
421
+ return {
422
+ modified: true,
423
+ appliedIndices,
424
+ appliedCount: appliedIndices.size,
425
+ diff: diffSummary,
426
+ };
427
+ }
428
+
429
+ const origText = fs.readFileSync(filePath, "utf8");
430
+ const { text: nextText, appliedIndices } = applyPatchesToTextDetailed(origText, doc, patches);
431
+ if (origText === nextText || appliedIndices.size === 0) {
432
+ return { modified: false, appliedIndices: new Set(), appliedCount: 0, diff: "" };
433
+ }
434
+
435
+ const diff = renderUnifiedDiff(diffLabel, origText, nextText);
436
+ if (!dryRun) {
437
+ atomicWriteBuffer(filePath, Buffer.from(nextText, "utf8"), { backup });
438
+ }
439
+ return {
440
+ modified: true,
441
+ appliedIndices,
442
+ appliedCount: appliedIndices.size,
443
+ diff,
444
+ };
445
+ }
446
+
447
+ function atomicWriteBuffer(filePath, buffer, { backup = false } = {}) {
448
+ const resolved = path.resolve(filePath);
449
+ const dir = path.dirname(resolved);
450
+ const mode = fs.existsSync(resolved) ? fs.statSync(resolved).mode : 0o644;
451
+
452
+ if (backup && fs.existsSync(resolved)) {
453
+ fs.copyFileSync(resolved, `${resolved}.bak`);
454
+ }
455
+
456
+ const tmpName = `.dislop-tmp-${process.pid}-${crypto.randomBytes(6).toString("hex")}`;
457
+ const tmpPath = path.join(dir, tmpName);
458
+ try {
459
+ fs.writeFileSync(tmpPath, buffer, { mode });
460
+ fs.renameSync(tmpPath, resolved);
461
+ } catch (err) {
462
+ if (fs.existsSync(tmpPath)) {
463
+ try {
464
+ fs.unlinkSync(tmpPath);
465
+ } catch {
466
+ // ignore cleanup failure
467
+ }
468
+ }
469
+ throw err;
470
+ }
471
+ }