dislop 0.9.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +7 -8
- package/.cursor-plugin/plugin.json +2 -3
- package/.pre-commit-hooks.yaml +5 -12
- package/PRODUCT.md +19 -63
- package/README.md +360 -252
- package/README.zh-CN.md +390 -240
- package/action.yml +30 -39
- package/bin/dislop-mcp.mjs +3 -4
- package/bin/dislop.mjs +4 -4594
- package/gemini-extension.json +2 -2
- package/llms-install.md +68 -0
- package/package.json +17 -63
- package/packs/common/artifact-qa/pack.json +5 -0
- package/packs/common/artifact-qa/prompts/rules.md +11 -0
- package/packs/common/artifact-qa/scripts/index.mjs +173 -0
- package/packs/common/slide-deck/pack.json +6 -0
- package/packs/common/slide-deck/prompts/rules.md +11 -0
- package/packs/common/slide-deck/scripts/index.mjs +62 -0
- package/packs/common/web-ui/pack.json +6 -0
- package/packs/common/web-ui/prompts/rules.md +11 -0
- package/packs/common/web-ui/scripts/index.mjs +80 -0
- package/packs/en/artifact-qa/pack.json +6 -0
- package/packs/en/artifact-qa/prompts/rules.md +14 -0
- package/packs/en/artifact-qa/scripts/index.mjs +90 -0
- package/packs/en/prose/pack.json +7 -0
- package/packs/en/prose/prompts/rules.md +26 -0
- package/packs/en/prose/scripts/index.mjs +290 -0
- package/packs/en/slide-deck/pack.json +7 -0
- package/packs/en/slide-deck/prompts/rules.md +17 -0
- package/packs/en/slide-deck/scripts/index.mjs +81 -0
- package/packs/en/web-ui/pack.json +7 -0
- package/packs/en/web-ui/prompts/rules.md +20 -0
- package/packs/en/web-ui/scripts/index.mjs +103 -0
- package/packs/zh/artifact-qa/pack.json +6 -0
- package/packs/zh/artifact-qa/prompts/rules.md +14 -0
- package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
- package/packs/zh/prose/pack.json +7 -0
- package/packs/zh/prose/prompts/rules.md +26 -0
- package/packs/zh/prose/scripts/index.mjs +305 -0
- package/packs/zh/slide-deck/pack.json +7 -0
- package/packs/zh/slide-deck/prompts/rules.md +17 -0
- package/packs/zh/slide-deck/scripts/index.mjs +75 -0
- package/packs/zh/web-ui/pack.json +7 -0
- package/packs/zh/web-ui/prompts/rules.md +20 -0
- package/packs/zh/web-ui/scripts/index.mjs +98 -0
- package/plugin.json +5 -6
- package/server.json +2 -2
- package/skills/deslop-docs/SKILL.md +10 -8
- package/skills/deslop-slides-docx/SKILL.md +7 -8
- package/skills/deslop-verify/SKILL.md +7 -8
- package/skills/deslop-web-ui/SKILL.md +7 -8
- package/skills/dislop/SKILL.md +16 -28
- package/skills/dislop/references/essay.md +1 -1
- package/skills/dislop/references/essay.zh-CN.md +1 -1
- package/skills/dislop/references/office.md +1 -1
- package/skills/dislop/references/office.zh-CN.md +1 -1
- package/skills/dislop/references/web-ui.md +1 -1
- package/skills/dislop/references/web-ui.zh-CN.md +1 -1
- package/skills/dislop/references/work-docs.md +1 -1
- package/skills/dislop/references/work-docs.zh-CN.md +1 -1
- package/src/cli-main.mjs +210 -0
- package/src/commands/check-fix.mjs +169 -0
- package/src/commands/doctor.mjs +110 -0
- package/src/commands/init.mjs +49 -0
- package/src/commands/login.mjs +82 -0
- package/src/commands/model.mjs +130 -0
- package/src/commands/packs.mjs +44 -0
- package/src/commands/verify.mjs +133 -0
- package/src/commands/voice.mjs +84 -0
- package/src/kernel/config.mjs +232 -0
- package/src/kernel/document-model.mjs +1412 -0
- package/src/kernel/fact-gate.mjs +615 -0
- package/src/kernel/file-discovery.mjs +139 -0
- package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
- package/src/kernel/pack-loader.mjs +715 -0
- package/src/kernel/patcher.mjs +341 -0
- package/src/kernel/pipeline.mjs +267 -0
- package/src/kernel/prompt-assembler.mjs +307 -0
- package/src/kernel/voice-profile.mjs +177 -0
- package/src/mcp/stdio-server.mjs +372 -0
- package/src/runners/auto-fix.mjs +59 -0
- package/src/runners/interactive-tty.mjs +461 -0
- package/src/runners/reporters.mjs +256 -0
- package/src/runtime/chunker.mjs +87 -0
- package/src/runtime/json-extract.mjs +144 -0
- package/src/runtime/privacy-gate.mjs +97 -0
- package/src/runtime/providers/anthropic.mjs +65 -0
- package/src/runtime/providers/cloud.mjs +136 -0
- package/src/runtime/providers/gemini.mjs +91 -0
- package/src/runtime/providers/local-model.mjs +139 -0
- package/src/runtime/providers/openai-compat.mjs +130 -0
- package/src/runtime/router.mjs +315 -0
- package/src/sdk/index.mjs +137 -0
- package/models/manifest.json +0 -90
- package/models/pocket-slop-v1.json +0 -1
- package/packs/business-brief/pack.json +0 -937
- package/packs/core/pack.json +0 -209
- package/packs/deck-and-ui/pack.json +0 -539
- package/packs/engineering-spec/pack.json +0 -144
- package/packs/executive-deck/pack.json +0 -98
- package/packs/literary-essay/pack.json +0 -344
- package/packs/regulated-comms/pack.json +0 -99
- package/patterns/ai-tic-rubric.json +0 -252
- package/patterns/banks/composite-fusion.json +0 -48
- package/patterns/banks/discourse-rhythm.json +0 -95
- package/patterns/banks/lexical-signals.json +0 -92
- package/patterns/banks/syntactic-frames.json +0 -52
- package/patterns/banks/visual-deck.json +0 -44
- package/patterns/dimensions/artifacts.json +0 -121
- package/patterns/dimensions/discourse.json +0 -438
- package/patterns/dimensions/lexical.json +0 -198
- package/patterns/dimensions/rhythm.json +0 -258
- package/patterns/dimensions/syntactic.json +0 -285
- package/patterns/dimensions/visual-and-deck.json +0 -530
- package/patterns/taxonomy.json +0 -112
- package/src/core.mjs +0 -5497
- package/src/dislop/review-picker.vim +0 -114
- package/src/local-model.mjs +0 -997
- package/src/pattern-engine.mjs +0 -1003
- package/src/pocket-model.mjs +0 -729
- package/src/review-apply.mjs +0 -151
- package/src/review-client.mjs +0 -1073
|
@@ -0,0 +1,341 @@
|
|
|
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, "<")
|
|
11
|
+
.replace(/>/g, ">");
|
|
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) {
|
|
52
|
+
const lf = patched.replace(/\r\n/g, "\n");
|
|
53
|
+
const 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
|
+
return eol === "\r\n" ? cleaned.replace(/\n/g, "\r\n") : cleaned;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function resolveLocatorForPatch(doc, patch) {
|
|
62
|
+
if (patch.locator) return patch.locator;
|
|
63
|
+
if (!patch.targetId) return null;
|
|
64
|
+
const seg = doc.segments.find((s) => s.id === patch.targetId);
|
|
65
|
+
if (seg?.locator) {
|
|
66
|
+
// If patch specifies originalQuote that is a substring inside the segment, narrow to exact quote if unique
|
|
67
|
+
if (patch.originalQuote && patch.originalQuote !== seg.text && seg.locator.kind !== "ooxml-span") {
|
|
68
|
+
const idx = seg.text.indexOf(patch.originalQuote);
|
|
69
|
+
if (idx !== -1 && seg.text.indexOf(patch.originalQuote, idx + 1) === -1) {
|
|
70
|
+
return {
|
|
71
|
+
...seg.locator,
|
|
72
|
+
start: seg.locator.start + idx,
|
|
73
|
+
end: seg.locator.start + idx + patch.originalQuote.length,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return seg.locator;
|
|
78
|
+
}
|
|
79
|
+
const para = doc.paragraphs?.find((p) => p.id === patch.targetId);
|
|
80
|
+
return para?.locator || null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Apply accepted patches (`Array<{ targetId?, locator?, originalQuote?, replacement: string }>`)
|
|
85
|
+
* to an in-memory UTF-8 text/markup document string.
|
|
86
|
+
*/
|
|
87
|
+
export function applyPatchesToText(sourceText, doc, patches) {
|
|
88
|
+
if (!patches || patches.length === 0) return sourceText;
|
|
89
|
+
const eol = detectEol(sourceText);
|
|
90
|
+
|
|
91
|
+
const resolved = [];
|
|
92
|
+
for (const patch of patches) {
|
|
93
|
+
const loc = resolveLocatorForPatch(doc, patch);
|
|
94
|
+
if (!loc || (loc.kind !== "text-span" && loc.kind !== "html-span")) continue;
|
|
95
|
+
let replacement = String(patch.replacement ?? "");
|
|
96
|
+
let span =
|
|
97
|
+
replacement === "" && loc.kind === "text-span"
|
|
98
|
+
? adjustTextSpanForDeletion(sourceText, loc.start, loc.end)
|
|
99
|
+
: { start: loc.start, end: loc.end };
|
|
100
|
+
// Narrow non-empty text-span replacements to their minimal differing slice so enclosing sentence rewrites
|
|
101
|
+
// never collide with non-overlapping inner defect deletions (e.g., trailing leaked citation tokens).
|
|
102
|
+
if (replacement !== "" && loc.kind === "text-span") {
|
|
103
|
+
const orig = sourceText.slice(span.start, span.end);
|
|
104
|
+
const minLen = Math.min(orig.length, replacement.length);
|
|
105
|
+
let cp = 0;
|
|
106
|
+
while (cp < minLen && orig[cp] === replacement[cp]) cp += 1;
|
|
107
|
+
let cs = 0;
|
|
108
|
+
while (cs < minLen - cp && orig[orig.length - 1 - cs] === replacement[replacement.length - 1 - cs]) cs += 1;
|
|
109
|
+
if (cp > 0 || cs > 0) {
|
|
110
|
+
span = { start: span.start + cp, end: span.end - cs };
|
|
111
|
+
replacement = replacement.slice(cp, replacement.length - cs);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
resolved.push({
|
|
115
|
+
start: span.start,
|
|
116
|
+
end: span.end,
|
|
117
|
+
replacement,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (resolved.length === 0) return sourceText;
|
|
122
|
+
|
|
123
|
+
// Sort in descending offset order and skip overlapping edits cleanly
|
|
124
|
+
resolved.sort((a, b) => b.start - a.start || b.end - a.end);
|
|
125
|
+
|
|
126
|
+
let out = sourceText;
|
|
127
|
+
let minAppliedStart = Infinity;
|
|
128
|
+
for (const edit of resolved) {
|
|
129
|
+
if (edit.end > minAppliedStart) continue; // overlap guard
|
|
130
|
+
out = out.slice(0, edit.start) + edit.replacement + out.slice(edit.end);
|
|
131
|
+
minAppliedStart = edit.start;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return normalizePostPatchWhitespace(out, eol);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function patchSingleOoxmlParagraphXml(pXml, nsPrefix, charEdits) {
|
|
138
|
+
const rTagRe = nsPrefix === "w" ? /<w:r\b[^>]*>[\s\S]*?<\/w:r>/g : /<a:r\b[^>]*>[\s\S]*?<\/a:r>/g;
|
|
139
|
+
const rPrTagRe = nsPrefix === "w" ? /<w:rPr\b[\s\S]*?<\/w:rPr>/ : /<a:rPr\b[\s\S]*?(?:\/>|<\/a:rPr>)/;
|
|
140
|
+
const tTagRe = nsPrefix === "w" ? /<w:t(?:\s+[^>]*)?>([\s\S]*?)<\/w:t>/g : /<a:t(?:\s+[^>]*)?>([\s\S]*?)<\/a:t>/g;
|
|
141
|
+
|
|
142
|
+
// Extract full text and preserve first run's rPr formatting
|
|
143
|
+
let firstRPr = "";
|
|
144
|
+
const rMatch = rTagRe.exec(pXml);
|
|
145
|
+
if (rMatch) {
|
|
146
|
+
const rPrMatch = rMatch[0].match(rPrTagRe);
|
|
147
|
+
if (rPrMatch) firstRPr = rPrMatch[0];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const pieces = [];
|
|
151
|
+
let tm;
|
|
152
|
+
while ((tm = tTagRe.exec(pXml)) !== null) {
|
|
153
|
+
pieces.push(decodeXmlEntities(tm[1]));
|
|
154
|
+
}
|
|
155
|
+
let fullText = pieces.join("");
|
|
156
|
+
|
|
157
|
+
// Apply edits in descending charStart order
|
|
158
|
+
const sorted = [...charEdits].sort((a, b) => b.charStart - a.charStart);
|
|
159
|
+
let minStart = Infinity;
|
|
160
|
+
for (const ed of sorted) {
|
|
161
|
+
if (ed.charEnd > minStart) continue;
|
|
162
|
+
let s = ed.charStart;
|
|
163
|
+
let e = ed.charEnd;
|
|
164
|
+
if (ed.replacement === "") {
|
|
165
|
+
if (e < fullText.length && fullText[e] === " ") e += 1;
|
|
166
|
+
else if (s > 0 && fullText[s - 1] === " ") s -= 1;
|
|
167
|
+
}
|
|
168
|
+
fullText = fullText.slice(0, s) + ed.replacement + fullText.slice(e);
|
|
169
|
+
minStart = s;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const pPrRe = nsPrefix === "w" ? /<w:pPr\b[\s\S]*?<\/w:pPr>/ : /<a:pPr\b[\s\S]*?(?:\/>|<\/a:pPr>)/;
|
|
173
|
+
const openTagMatch = pXml.match(/^<(?:w|a):p\b[^>]*>/);
|
|
174
|
+
const openTag = openTagMatch ? openTagMatch[0] : `<${nsPrefix}:p>`;
|
|
175
|
+
const pPrMatch = pXml.match(pPrRe);
|
|
176
|
+
const pPr = pPrMatch ? pPrMatch[0] : "";
|
|
177
|
+
|
|
178
|
+
if (!fullText.trim()) {
|
|
179
|
+
return `${openTag}${pPr}</${nsPrefix}:p>`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const escaped = escapeXmlText(fullText);
|
|
183
|
+
if (nsPrefix === "w") {
|
|
184
|
+
return `${openTag}${pPr}<w:r>${firstRPr}<w:t xml:space="preserve">${escaped}</w:t></w:r></w:p>`;
|
|
185
|
+
}
|
|
186
|
+
return `${openTag}${pPr}<a:r>${firstRPr}<a:t>${escaped}</a:t></a:r></a:p>`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Apply accepted patches to an OOXML (`.docx` / `.pptx`) archive buffer, returning a new Buffer.
|
|
191
|
+
*/
|
|
192
|
+
export function applyPatchesToOoxmlBuffer(originalBuffer, doc, patches) {
|
|
193
|
+
if (!patches || patches.length === 0) return originalBuffer;
|
|
194
|
+
const { xmlEntries } = readZipArchive(originalBuffer);
|
|
195
|
+
|
|
196
|
+
// Group edits by entryName -> paragraphOrd
|
|
197
|
+
const byEntry = new Map();
|
|
198
|
+
for (const patch of patches) {
|
|
199
|
+
const loc = resolveLocatorForPatch(doc, patch);
|
|
200
|
+
if (!loc || loc.kind !== "ooxml-span") continue;
|
|
201
|
+
let entryGroup = byEntry.get(loc.entryName);
|
|
202
|
+
if (!entryGroup) {
|
|
203
|
+
entryGroup = { nsPrefix: loc.nsPrefix, byPara: new Map() };
|
|
204
|
+
byEntry.set(loc.entryName, entryGroup);
|
|
205
|
+
}
|
|
206
|
+
let paraEdits = entryGroup.byPara.get(loc.paragraphOrd);
|
|
207
|
+
if (!paraEdits) {
|
|
208
|
+
paraEdits = [];
|
|
209
|
+
entryGroup.byPara.set(loc.paragraphOrd, paraEdits);
|
|
210
|
+
}
|
|
211
|
+
paraEdits.push({
|
|
212
|
+
charStart: loc.charStart,
|
|
213
|
+
charEnd: loc.charEnd,
|
|
214
|
+
replacement: String(patch.replacement ?? ""),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (byEntry.size === 0) return originalBuffer;
|
|
219
|
+
|
|
220
|
+
const updatedXml = {};
|
|
221
|
+
for (const [entryName, group] of byEntry.entries()) {
|
|
222
|
+
const xml = xmlEntries[entryName];
|
|
223
|
+
if (!xml) continue;
|
|
224
|
+
const pTagRe =
|
|
225
|
+
group.nsPrefix === "w" ? /<w:p\b[^>]*>[\s\S]*?<\/w:p>/g : /<a:p\b[^>]*>[\s\S]*?<\/a:p>/g;
|
|
226
|
+
let pOrd = 0;
|
|
227
|
+
updatedXml[entryName] = xml.replace(pTagRe, (pXml) => {
|
|
228
|
+
const idx = pOrd;
|
|
229
|
+
pOrd += 1;
|
|
230
|
+
const edits = group.byPara.get(idx);
|
|
231
|
+
if (!edits || edits.length === 0) return pXml;
|
|
232
|
+
return patchSingleOoxmlParagraphXml(pXml, group.nsPrefix, edits);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return repackZipArchive(originalBuffer, updatedXml);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Render a compact unified diff preview between `beforeText` and `afterText`.
|
|
241
|
+
*/
|
|
242
|
+
export function renderUnifiedDiff(filePath, beforeText, afterText) {
|
|
243
|
+
if (beforeText === afterText) return "";
|
|
244
|
+
const aLines = beforeText.replace(/\r\n/g, "\n").split("\n");
|
|
245
|
+
const bLines = afterText.replace(/\r\n/g, "\n").split("\n");
|
|
246
|
+
|
|
247
|
+
const out = [`--- a/${filePath}`, `+++ b/${filePath}`];
|
|
248
|
+
const maxLen = Math.max(aLines.length, bLines.length);
|
|
249
|
+
let i = 0;
|
|
250
|
+
while (i < maxLen) {
|
|
251
|
+
if (aLines[i] === bLines[i]) {
|
|
252
|
+
i += 1;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const start = Math.max(0, i - 1);
|
|
256
|
+
let endA = i;
|
|
257
|
+
let endB = i;
|
|
258
|
+
while (endA < aLines.length || endB < bLines.length) {
|
|
259
|
+
if (endA < aLines.length && endB < bLines.length && aLines[endA] === bLines[endB]) break;
|
|
260
|
+
if (endA < aLines.length) endA += 1;
|
|
261
|
+
if (endB < bLines.length) endB += 1;
|
|
262
|
+
}
|
|
263
|
+
out.push(`@@ -${start + 1},${endA - start} +${start + 1},${endB - start} @@`);
|
|
264
|
+
if (start < i) out.push(` ${aLines[start]}`);
|
|
265
|
+
for (let k = i; k < endA; k += 1) {
|
|
266
|
+
if (aLines[k] !== undefined) out.push(`-${aLines[k]}`);
|
|
267
|
+
}
|
|
268
|
+
for (let k = i; k < endB; k += 1) {
|
|
269
|
+
if (bLines[k] !== undefined) out.push(`+${bLines[k]}`);
|
|
270
|
+
}
|
|
271
|
+
i = Math.max(endA, endB);
|
|
272
|
+
}
|
|
273
|
+
return out.join("\n");
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Apply patches to `doc.filePath` (supporting `--dry-run` and `--backup` atomic temp-file rename).
|
|
278
|
+
*/
|
|
279
|
+
export function patchDocumentOnDisk(doc, patches, { dryRun = false, backup = false, displayPath = null } = {}) {
|
|
280
|
+
if (!patches || patches.length === 0) {
|
|
281
|
+
return { modified: false, diff: "" };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const filePath = doc.filePath;
|
|
285
|
+
const diffLabel = (displayPath || filePath).replace(/^\/+/, "");
|
|
286
|
+
if (doc.format === "docx" || doc.format === "pptx") {
|
|
287
|
+
const origBuf = fs.readFileSync(filePath);
|
|
288
|
+
const nextBuf = applyPatchesToOoxmlBuffer(origBuf, doc, patches);
|
|
289
|
+
if (origBuf.equals(nextBuf)) {
|
|
290
|
+
return { modified: false, diff: "" };
|
|
291
|
+
}
|
|
292
|
+
const diffSummary = patches
|
|
293
|
+
.map(
|
|
294
|
+
(p) =>
|
|
295
|
+
`--- a/${diffLabel} [${p.targetId || "ooxml"}]\n+++ b/${diffLabel} [${p.targetId || "ooxml"}]\n-${p.originalQuote || ""}\n+${p.replacement || "(deleted)"}`,
|
|
296
|
+
)
|
|
297
|
+
.join("\n");
|
|
298
|
+
if (!dryRun) {
|
|
299
|
+
atomicWriteBuffer(filePath, nextBuf, { backup });
|
|
300
|
+
}
|
|
301
|
+
return { modified: true, diff: diffSummary };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const origText = fs.readFileSync(filePath, "utf8");
|
|
305
|
+
const nextText = applyPatchesToText(origText, doc, patches);
|
|
306
|
+
if (origText === nextText) {
|
|
307
|
+
return { modified: false, diff: "" };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const diff = renderUnifiedDiff(diffLabel, origText, nextText);
|
|
311
|
+
if (!dryRun) {
|
|
312
|
+
atomicWriteBuffer(filePath, Buffer.from(nextText, "utf8"), { backup });
|
|
313
|
+
}
|
|
314
|
+
return { modified: true, diff };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function atomicWriteBuffer(filePath, buffer, { backup = false } = {}) {
|
|
318
|
+
const resolved = path.resolve(filePath);
|
|
319
|
+
const dir = path.dirname(resolved);
|
|
320
|
+
const mode = fs.existsSync(resolved) ? fs.statSync(resolved).mode : 0o644;
|
|
321
|
+
|
|
322
|
+
if (backup && fs.existsSync(resolved)) {
|
|
323
|
+
fs.copyFileSync(resolved, `${resolved}.bak`);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const tmpName = `.dislop-tmp-${process.pid}-${crypto.randomBytes(6).toString("hex")}`;
|
|
327
|
+
const tmpPath = path.join(dir, tmpName);
|
|
328
|
+
try {
|
|
329
|
+
fs.writeFileSync(tmpPath, buffer, { mode });
|
|
330
|
+
fs.renameSync(tmpPath, resolved);
|
|
331
|
+
} catch (err) {
|
|
332
|
+
if (fs.existsSync(tmpPath)) {
|
|
333
|
+
try {
|
|
334
|
+
fs.unlinkSync(tmpPath);
|
|
335
|
+
} catch {
|
|
336
|
+
// ignore cleanup failure
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
throw err;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { DislopConfigError } from "./config.mjs";
|
|
3
|
+
import { parseDocumentFile } from "./document-model.mjs";
|
|
4
|
+
import { applyDualFactGate } from "./fact-gate.mjs";
|
|
5
|
+
import { resolveActivePacks, runDeterministicPackChecks } from "./pack-loader.mjs";
|
|
6
|
+
import {
|
|
7
|
+
assemblePromptPayload,
|
|
8
|
+
collectPackPromptRules,
|
|
9
|
+
normalizeLlmResponseItems,
|
|
10
|
+
} from "./prompt-assembler.mjs";
|
|
11
|
+
import { buildSlidingWindowChunks } from "../runtime/chunker.mjs";
|
|
12
|
+
|
|
13
|
+
const DEFECT_SEVERITY_RANK = Object.freeze({
|
|
14
|
+
error: 1,
|
|
15
|
+
warning: 2,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const SUGGESTION_PRIORITY_RANK = Object.freeze({
|
|
19
|
+
strong: 1,
|
|
20
|
+
moderate: 2,
|
|
21
|
+
hint: 3,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const LEVEL_THRESHOLD_MAX_RANK = Object.freeze({
|
|
25
|
+
strong: 1,
|
|
26
|
+
moderate: 2,
|
|
27
|
+
hint: 3,
|
|
28
|
+
all: 3,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export function getItemTierKey(item) {
|
|
32
|
+
if (item.kind === "defect") {
|
|
33
|
+
return `defect:${item.severity || "error"}`;
|
|
34
|
+
}
|
|
35
|
+
return `suggestion:${item.priority || "moderate"}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function buildSegmentOrderMap(doc) {
|
|
39
|
+
const map = new Map();
|
|
40
|
+
doc.segments.forEach((seg, idx) => {
|
|
41
|
+
map.set(seg.id, idx);
|
|
42
|
+
});
|
|
43
|
+
return map;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function finalizeReportItems(rawItems, doc, { level = "all" } = {}) {
|
|
47
|
+
const maxSuggestionRank = LEVEL_THRESHOLD_MAX_RANK[level] ?? 3;
|
|
48
|
+
const segOrder = buildSegmentOrderMap(doc);
|
|
49
|
+
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
const deduped = [];
|
|
52
|
+
|
|
53
|
+
for (const item of rawItems) {
|
|
54
|
+
if (item.kind === "suggestion") {
|
|
55
|
+
const pRank = SUGGESTION_PRIORITY_RANK[item.priority] ?? 2;
|
|
56
|
+
if (pRank > maxSuggestionRank) continue;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const dedupeKey = `${item.targetId || `line:${item.line || 0}:${item.originalQuote}`}::${item.ruleId}`;
|
|
60
|
+
if (seen.has(dedupeKey)) continue;
|
|
61
|
+
seen.add(dedupeKey);
|
|
62
|
+
deduped.push(item);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
deduped.sort((a, b) => {
|
|
66
|
+
if (a.kind !== b.kind) {
|
|
67
|
+
return a.kind === "defect" ? -1 : 1;
|
|
68
|
+
}
|
|
69
|
+
if (a.kind === "defect") {
|
|
70
|
+
const sa = DEFECT_SEVERITY_RANK[a.severity] ?? 9;
|
|
71
|
+
const sb = DEFECT_SEVERITY_RANK[b.severity] ?? 9;
|
|
72
|
+
if (sa !== sb) return sa - sb;
|
|
73
|
+
} else {
|
|
74
|
+
const pa = SUGGESTION_PRIORITY_RANK[a.priority] ?? 9;
|
|
75
|
+
const pb = SUGGESTION_PRIORITY_RANK[b.priority] ?? 9;
|
|
76
|
+
if (pa !== pb) return pa - pb;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const ordA = a.targetId && segOrder.has(a.targetId) ? segOrder.get(a.targetId) : Number.MAX_SAFE_INTEGER;
|
|
80
|
+
const ordB = b.targetId && segOrder.has(b.targetId) ? segOrder.get(b.targetId) : Number.MAX_SAFE_INTEGER;
|
|
81
|
+
if (ordA !== ordB) return ordA - ordB;
|
|
82
|
+
return (a.line || 0) - (b.line || 0);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return deduped.map((item, idx) => ({
|
|
86
|
+
id: `item-${idx + 1}`,
|
|
87
|
+
...item,
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function computeSummaryCounts(items) {
|
|
92
|
+
const summary = {
|
|
93
|
+
defects: { error: 0, warning: 0 },
|
|
94
|
+
suggestions: { strong: 0, moderate: 0, hint: 0 },
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
for (const item of items) {
|
|
98
|
+
if (item._applied) continue;
|
|
99
|
+
if (item.kind === "defect") {
|
|
100
|
+
if (item.severity === "error") summary.defects.error += 1;
|
|
101
|
+
else summary.defects.warning += 1;
|
|
102
|
+
} else if (item.kind === "suggestion") {
|
|
103
|
+
if (item.priority === "strong") summary.suggestions.strong += 1;
|
|
104
|
+
else if (item.priority === "hint") summary.suggestions.hint += 1;
|
|
105
|
+
else summary.suggestions.moderate += 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return summary;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function serializeCleanReportItem(item) {
|
|
113
|
+
return {
|
|
114
|
+
id: item.id,
|
|
115
|
+
kind: item.kind,
|
|
116
|
+
pack: item.pack,
|
|
117
|
+
ruleId: item.ruleId,
|
|
118
|
+
targetId: item.targetId,
|
|
119
|
+
...(item.line !== undefined ? { line: item.line } : {}),
|
|
120
|
+
...(item.kind === "defect" ? { severity: item.severity } : { priority: item.priority }),
|
|
121
|
+
fixSafety: item.fixSafety,
|
|
122
|
+
actionType: item.actionType,
|
|
123
|
+
originalQuote: item.originalQuote,
|
|
124
|
+
suggestedReplacement: item.suggestedReplacement,
|
|
125
|
+
reason: item.reason,
|
|
126
|
+
...(item.rewritePrompt ? { rewritePrompt: item.rewritePrompt } : {}),
|
|
127
|
+
...(item.verificationNote ? { verificationNote: item.verificationNote } : {}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Execute Steps 2-6 of the 7-Step Kernel Pipeline for a single target file.
|
|
133
|
+
* Enforces lazy stage-gated loading:
|
|
134
|
+
* - Step 3 imports `scripts/` ONLY for admitted Packs with `hasScripts`.
|
|
135
|
+
* - Step 4 reads/compiles `prompts/` ONLY when `!config.noLlm` AND `route.execute` is active!
|
|
136
|
+
*/
|
|
137
|
+
export async function runDocumentPipeline({
|
|
138
|
+
filePath,
|
|
139
|
+
config,
|
|
140
|
+
route,
|
|
141
|
+
voiceProfile = null,
|
|
142
|
+
cwd = process.cwd(),
|
|
143
|
+
}) {
|
|
144
|
+
// Step 2: Document Parsing & Physical Coordinate Modeling
|
|
145
|
+
let doc;
|
|
146
|
+
try {
|
|
147
|
+
doc = parseDocumentFile(filePath);
|
|
148
|
+
} catch (err) {
|
|
149
|
+
throw new DislopConfigError(err.message);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const diagnosticLang = config.lang && config.lang !== "auto" ? config.lang : doc.language;
|
|
153
|
+
|
|
154
|
+
// Step 3: Zero-Import Metadata Admission + Lazy `scripts/` Execution
|
|
155
|
+
let activePacks;
|
|
156
|
+
try {
|
|
157
|
+
activePacks = await resolveActivePacks(doc, {
|
|
158
|
+
packSpecifiers: config.packs,
|
|
159
|
+
cwd,
|
|
160
|
+
});
|
|
161
|
+
} catch (err) {
|
|
162
|
+
throw new DislopConfigError(err.message);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const deterministicItems = await runDeterministicPackChecks(doc, activePacks, {
|
|
166
|
+
diagnosticLang,
|
|
167
|
+
cwd,
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// Step 4: Lazy `prompts/` Loading & 3-Tier LLM Evaluation (ONLY when an LLM route is active!)
|
|
171
|
+
const anyPackHasPrompts = activePacks.some((p) => p.hasPrompts);
|
|
172
|
+
let llmItems = [];
|
|
173
|
+
let documentToneAnchor = "";
|
|
174
|
+
let engineUsed = "deterministic";
|
|
175
|
+
let routeHint = null;
|
|
176
|
+
|
|
177
|
+
if (!config.noLlm && anyPackHasPrompts && doc.segments.length > 0) {
|
|
178
|
+
if (route && typeof route.execute === "function") {
|
|
179
|
+
// Lazily read & compile `prompts/*.md` now that we know an LLM call will actually run
|
|
180
|
+
const { rules: promptRules, roleHints } = await collectPackPromptRules(doc, activePacks, {
|
|
181
|
+
diagnosticLang,
|
|
182
|
+
cwd,
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
if (promptRules.length > 0) {
|
|
186
|
+
engineUsed = route.engineLabel;
|
|
187
|
+
const chunks = buildSlidingWindowChunks(doc, {
|
|
188
|
+
maxInputTokens: route.maxInputTokens || 12000,
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
for (const chunk of chunks) {
|
|
192
|
+
const payload = assemblePromptPayload({
|
|
193
|
+
doc,
|
|
194
|
+
promptRules,
|
|
195
|
+
roleHints,
|
|
196
|
+
voiceProfile,
|
|
197
|
+
chunk,
|
|
198
|
+
globalToneAnchor: documentToneAnchor || null,
|
|
199
|
+
diagnosticLang,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
try {
|
|
203
|
+
const rawResponse = await route.execute(payload, doc, promptRules);
|
|
204
|
+
const normalized = normalizeLlmResponseItems(rawResponse, {
|
|
205
|
+
doc,
|
|
206
|
+
chunkSegments: chunk.segments,
|
|
207
|
+
promptRules,
|
|
208
|
+
});
|
|
209
|
+
if (!documentToneAnchor && normalized.documentToneAnchor) {
|
|
210
|
+
documentToneAnchor = normalized.documentToneAnchor;
|
|
211
|
+
}
|
|
212
|
+
llmItems.push(...normalized.items);
|
|
213
|
+
} catch (err) {
|
|
214
|
+
if (err?.authError || config.explicitEngine) {
|
|
215
|
+
throw new DislopConfigError(err.message);
|
|
216
|
+
}
|
|
217
|
+
engineUsed = "deterministic";
|
|
218
|
+
routeHint = err?.ollamaMissing
|
|
219
|
+
? "💡 Ollama is missing on this machine; showing deterministic checks only. Install Ollama (https://ollama.com) for Tier 3 local LLM checks."
|
|
220
|
+
: "💡 Local Ollama runtime unreachable (is 'ollama serve' running?); showing deterministic checks only.";
|
|
221
|
+
llmItems = [];
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
} else if (route?.hint) {
|
|
227
|
+
// Notice: `prompts/*.md` are NOT read at all when falling back to deterministic mode!
|
|
228
|
+
routeHint = route.hint;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Step 5: Dual Post-LLM Fact Gate (lazily invokes `scripts/` `verifyFix` if present)
|
|
233
|
+
const combinedRaw = [...deterministicItems, ...llmItems];
|
|
234
|
+
const gatedItems = await applyDualFactGate(combinedRaw, doc, activePacks);
|
|
235
|
+
|
|
236
|
+
const orderedItems = finalizeReportItems(gatedItems, doc, { level: config.level || "all" });
|
|
237
|
+
const summary = computeSummaryCounts(orderedItems);
|
|
238
|
+
const relDisplayPath = path.relative(cwd, path.resolve(cwd, filePath)) || filePath;
|
|
239
|
+
|
|
240
|
+
const report = {
|
|
241
|
+
schema: "dislop.report/1",
|
|
242
|
+
file: relDisplayPath.replace(/\\/g, "/"),
|
|
243
|
+
language: doc.language,
|
|
244
|
+
engine: engineUsed,
|
|
245
|
+
mountedPacks: activePacks.map((p) => p.name),
|
|
246
|
+
documentToneAnchor,
|
|
247
|
+
summary,
|
|
248
|
+
items: orderedItems.map(serializeCleanReportItem),
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
doc,
|
|
253
|
+
activePacks,
|
|
254
|
+
report,
|
|
255
|
+
items: orderedItems,
|
|
256
|
+
routeHint,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function arbitrateExitCode(reports) {
|
|
261
|
+
for (const r of reports) {
|
|
262
|
+
if ((r.summary?.defects?.error || 0) > 0) {
|
|
263
|
+
return 1;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return 0;
|
|
267
|
+
}
|