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,801 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { DislopConfigError } from "./config.mjs";
6
+ import { validatePackPath } from "./pack-validator.mjs";
7
+ import {
8
+ VALID_ACTION_TYPES,
9
+ VALID_DEFECT_SEVERITIES,
10
+ VALID_FIX_SAFETIES,
11
+ VALID_SUGGESTION_PRIORITIES,
12
+ definePack,
13
+ definePackScripts,
14
+ } from "../sdk/index.mjs";
15
+
16
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
17
+ export const BUILTIN_PACKS_ROOT = path.resolve(__dirname, "..", "..", "packs");
18
+
19
+ const SHORTHAND_ALIASES = Object.freeze({
20
+ "prose-en": "en/prose",
21
+ "prose-zh": "zh/prose",
22
+ "artifact-qa-en": "en/artifact-qa",
23
+ "artifact-qa-zh": "zh/artifact-qa",
24
+ "web-ui-en": "en/web-ui",
25
+ "web-ui-zh": "zh/web-ui",
26
+ "slide-deck-en": "en/slide-deck",
27
+ "slide-deck-zh": "zh/slide-deck",
28
+ });
29
+
30
+ function parseInlineArray(raw) {
31
+ const inner = raw.trim().replace(/^\[/, "").replace(/\]$/, "").trim();
32
+ if (!inner) return [];
33
+ return inner
34
+ .split(",")
35
+ .map((s) => s.trim().replace(/^["']|["']$/g, ""))
36
+ .filter(Boolean);
37
+ }
38
+
39
+ function unquoteYamlScalar(raw) {
40
+ return String(raw || "")
41
+ .trim()
42
+ .replace(/^["']|["']$/g, "");
43
+ }
44
+
45
+ /**
46
+ * Parse a Markdown prompt file (`prompts/*.md` or `<name>.pack.md`) into `{ meta, roleHint, rules }`.
47
+ */
48
+ export function parseMarkdownPromptContent(markdownText, sourcePath = "rules.md") {
49
+ const normalized = String(markdownText || "").replace(/\r\n/g, "\n");
50
+ const fmMatch = normalized.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
51
+
52
+ let fmLines = [];
53
+ let body = normalized.trim();
54
+ if (fmMatch) {
55
+ fmLines = fmMatch[1].split("\n");
56
+ body = fmMatch[2].trim();
57
+ }
58
+
59
+ let name = path
60
+ .basename(sourcePath)
61
+ .replace(/\.pack\.md$/i, "")
62
+ .replace(/\.md$/i, "");
63
+ let version = "0.1.0";
64
+ let description = "";
65
+ let roleHint = "";
66
+ let languages;
67
+ let formats;
68
+ let modalities;
69
+ const frontmatterRules = [];
70
+
71
+ let inRulesList = false;
72
+ let currentRule = null;
73
+
74
+ for (const rawLine of fmLines) {
75
+ const line = rawLine.replace(/#.*$/, "").trimEnd();
76
+ if (!line.trim()) continue;
77
+
78
+ if (inRulesList) {
79
+ const itemStart = line.match(/^\s*-\s+([a-zA-Z0-9_-]+)\s*:\s*(.+)$/);
80
+ if (itemStart) {
81
+ if (currentRule) frontmatterRules.push(currentRule);
82
+ currentRule = { [itemStart[1]]: unquoteYamlScalar(itemStart[2]) };
83
+ continue;
84
+ }
85
+ const itemProp = line.match(/^\s{2,}([a-zA-Z0-9_-]+)\s*:\s*(.+)$/);
86
+ if (itemProp && currentRule) {
87
+ currentRule[itemProp[1]] = unquoteYamlScalar(itemProp[2]);
88
+ continue;
89
+ }
90
+ if (!/^\s/.test(line)) {
91
+ if (currentRule) {
92
+ frontmatterRules.push(currentRule);
93
+ currentRule = null;
94
+ }
95
+ inRulesList = false;
96
+ }
97
+ }
98
+
99
+ const kv = line.match(/^([a-zA-Z0-9_-]+)\s*:\s*(.*)$/);
100
+ if (!kv) continue;
101
+ const [, key, val] = kv;
102
+ if (key === "rules" && !val.trim()) {
103
+ inRulesList = true;
104
+ continue;
105
+ }
106
+ if (key === "name" && val.trim()) name = unquoteYamlScalar(val);
107
+ else if (key === "version" && val.trim()) version = unquoteYamlScalar(val);
108
+ else if (key === "description" && val.trim()) description = unquoteYamlScalar(val);
109
+ else if (key === "roleHint" && val.trim()) roleHint = unquoteYamlScalar(val);
110
+ else if (key === "languages") languages = parseInlineArray(val);
111
+ else if (key === "formats") formats = parseInlineArray(val);
112
+ else if (key === "modalities") modalities = parseInlineArray(val);
113
+ }
114
+ if (currentRule) frontmatterRules.push(currentRule);
115
+
116
+ const bodyMap = new Map();
117
+ const bodyOrdered = [];
118
+ const ruleLineRe = /^(?:\d+\.|[-*+])\s+\*\*([a-zA-Z0-9._-]+)\*\*\s*:\s*(.+)$/gm;
119
+ let m;
120
+ while ((m = ruleLineRe.exec(body)) !== null) {
121
+ const id = m[1].trim();
122
+ const instruction = m[2].trim();
123
+ bodyMap.set(id, instruction);
124
+ bodyOrdered.push({ id, instruction });
125
+ }
126
+
127
+ const compiledRules = [];
128
+ if (frontmatterRules.length > 0) {
129
+ for (const r of frontmatterRules) {
130
+ const ruleId = r.id || r.ruleId;
131
+ if (!ruleId) continue;
132
+ const priority = VALID_SUGGESTION_PRIORITIES.includes(r.priority) ? r.priority : "moderate";
133
+ const instruction = r.instruction || bodyMap.get(ruleId) || body;
134
+ compiledRules.push({
135
+ ruleId,
136
+ defaultPriority: priority,
137
+ instruction,
138
+ });
139
+ }
140
+ } else if (bodyOrdered.length > 0) {
141
+ for (const r of bodyOrdered) {
142
+ compiledRules.push({
143
+ ruleId: r.id,
144
+ defaultPriority: "moderate",
145
+ instruction: r.instruction,
146
+ });
147
+ }
148
+ } else if (body) {
149
+ compiledRules.push({
150
+ ruleId: "general",
151
+ defaultPriority: "moderate",
152
+ instruction: body,
153
+ });
154
+ }
155
+
156
+ return {
157
+ meta: { name, version, description, languages, formats, modalities },
158
+ roleHint,
159
+ rules: compiledRules,
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Compile a standalone single-file `<name>.pack.md` into a Pack handle.
165
+ */
166
+ export function compileMarkdownPack(markdownText, sourcePath = "custom.pack.md") {
167
+ const normalized = String(markdownText || "").replace(/\r\n/g, "\n");
168
+ if (!/^---\n[\s\S]*?\n---/.test(normalized)) {
169
+ throw new Error(`Invalid Markdown Pack '${sourcePath}': missing YAML frontmatter block (--- ... ---)`);
170
+ }
171
+ const parsed = parseMarkdownPromptContent(normalized, sourcePath);
172
+ const pack = definePack({
173
+ name: parsed.meta.name,
174
+ version: parsed.meta.version,
175
+ description:
176
+ parsed.meta.description || `Declarative Markdown Prompt Pack (${path.basename(sourcePath)})`,
177
+ ...(parsed.meta.languages ? { languages: parsed.meta.languages } : {}),
178
+ ...(parsed.meta.formats ? { formats: parsed.meta.formats } : {}),
179
+ ...(parsed.meta.modalities ? { modalities: parsed.meta.modalities } : {}),
180
+ resolvePrompt(doc) {
181
+ return {
182
+ ...(parsed.roleHint ? { roleHint: interpolateRoleHint(parsed.roleHint, doc) } : {}),
183
+ rules: parsed.rules,
184
+ };
185
+ },
186
+ });
187
+ return wrapEagerPackAsLazyHandle(pack);
188
+ }
189
+
190
+ /**
191
+ * Interpolate lightweight document telemetry placeholders (`{{uiSummary}}`, `{{deckSummary}}`)
192
+ * inside Markdown prompt `roleHint` strings so `prompts/*.md` stays 100% pure Markdown.
193
+ */
194
+ export function interpolateRoleHint(template, doc) {
195
+ if (!template || !template.includes("{{")) return template;
196
+ return template
197
+ .replace(/\{\{\s*uiSummary\s*\}\}/g, () => {
198
+ const ui = doc?.artifacts?.uiSignals || {};
199
+ return `UI telemetry: pillBadges=${(ui.pillBadges || []).length}, gradients=${(ui.purplePinkGradients || []).length}, links=${(doc?.artifacts?.links || []).length}.`;
200
+ })
201
+ .replace(/\{\{\s*deckSummary\s*\}\}/g, () => {
202
+ const slides = doc?.artifacts?.deckSignals?.slides || [];
203
+ if (slides.length === 0) return "";
204
+ return `Deck structure (${slides.length} slides): ${slides
205
+ .slice(0, 15)
206
+ .map((s) => `S${s.index}("${String(s.title || "").slice(0, 40)}", words=${s.wordCount}, bullets=${s.bulletCount})`)
207
+ .join("; ")}.`;
208
+ })
209
+ .replace(/\{\{\s*slideCount\s*\}\}/g, () => {
210
+ const c = doc?.artifacts?.deckSignals?.slideCount;
211
+ return c ? String(c) : "0";
212
+ })
213
+ .trim();
214
+ }
215
+
216
+ function listFilesWithExt(dirPath, extRegex) {
217
+ if (!fs.existsSync(dirPath) || !fs.statSync(dirPath).isDirectory()) return [];
218
+ return fs
219
+ .readdirSync(dirPath, { withFileTypes: true })
220
+ .filter((e) => e.isFile() && extRegex.test(e.name))
221
+ .map((e) => path.join(dirPath, e.name))
222
+ .sort();
223
+ }
224
+
225
+ /**
226
+ * Create a lazy stage-gated Pack Handle for a separated Pack directory:
227
+ * `<packDir>/pack.json`
228
+ * `<packDir>/scripts/*.mjs` (imported ONLY when deterministic checks or verifyFix run)
229
+ * `<packDir>/prompts/*.md` (read & compiled ONLY when an LLM route is active)
230
+ */
231
+ export function createDirectoryPackHandle(packDir) {
232
+ const manifestPath = path.join(packDir, "pack.json");
233
+ if (!fs.existsSync(manifestPath)) {
234
+ throw new Error(`Pack directory '${packDir}' is missing pack.json`);
235
+ }
236
+ const rawManifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
237
+ const name = String(rawManifest.name || "").trim();
238
+ if (!name) {
239
+ throw new Error(`Invalid pack.json in '${packDir}': missing 'name'`);
240
+ }
241
+
242
+ const version = String(rawManifest.version || "1.0.0").trim();
243
+ const description = String(rawManifest.description || "").trim();
244
+ const languages = Array.isArray(rawManifest.languages)
245
+ ? Object.freeze(rawManifest.languages.map((l) => String(l).trim().toLowerCase()).filter(Boolean))
246
+ : null;
247
+ const formats = Array.isArray(rawManifest.formats)
248
+ ? Object.freeze(
249
+ rawManifest.formats.map((f) => String(f).trim().toLowerCase().replace(/^\./, "")).filter(Boolean),
250
+ )
251
+ : null;
252
+ const modalities = Array.isArray(rawManifest.modalities)
253
+ ? Object.freeze(rawManifest.modalities.map((m) => String(m).trim().toLowerCase()).filter(Boolean))
254
+ : null;
255
+
256
+ const scriptsDir = path.join(packDir, "scripts");
257
+ const promptsDir = path.join(packDir, "prompts");
258
+
259
+ const scriptFiles = listFilesWithExt(scriptsDir, /\.(?:mjs|js)$/i);
260
+ const promptFiles = listFilesWithExt(promptsDir, /\.md$/i);
261
+
262
+ const loadStats = {
263
+ scriptsLoaded: false,
264
+ promptsLoaded: false,
265
+ scriptFileCount: scriptFiles.length,
266
+ promptFileCount: promptFiles.length,
267
+ };
268
+
269
+ let cachedScriptsPromise = null;
270
+ let cachedPromptsPromise = null;
271
+
272
+ return Object.freeze({
273
+ __dislopPack: true,
274
+ __lazyPackHandle: true,
275
+ packDir,
276
+ name,
277
+ version,
278
+ description,
279
+ languages,
280
+ formats,
281
+ modalities,
282
+ hasScripts: scriptFiles.length > 0,
283
+ hasPrompts: promptFiles.length > 0,
284
+ loadStats,
285
+
286
+ async loadScripts() {
287
+ if (scriptFiles.length === 0) return [];
288
+ if (!cachedScriptsPromise) {
289
+ cachedScriptsPromise = (async () => {
290
+ const modules = [];
291
+ for (const sf of scriptFiles) {
292
+ const mod = await import(pathToFileURL(sf).href);
293
+ const exported = mod.default || mod;
294
+ const normalized = exported?.__dislopPackScripts
295
+ ? exported
296
+ : definePackScripts({
297
+ appliesTo: exported?.appliesTo || mod.appliesTo,
298
+ check: exported?.check || mod.check,
299
+ verifyFix: exported?.verifyFix || mod.verifyFix,
300
+ });
301
+ modules.push(normalized);
302
+ }
303
+ loadStats.scriptsLoaded = true;
304
+ return modules;
305
+ })();
306
+ }
307
+ return cachedScriptsPromise;
308
+ },
309
+
310
+ async loadPrompts() {
311
+ if (promptFiles.length === 0) return [];
312
+ if (!cachedPromptsPromise) {
313
+ cachedPromptsPromise = (async () => {
314
+ const parsedPrompts = promptFiles.map((pf) => {
315
+ const raw = fs.readFileSync(pf, "utf8");
316
+ return parseMarkdownPromptContent(raw, pf);
317
+ });
318
+ loadStats.promptsLoaded = true;
319
+ return parsedPrompts;
320
+ })();
321
+ }
322
+ return cachedPromptsPromise;
323
+ },
324
+ });
325
+ }
326
+
327
+ /**
328
+ * Wrap an in-memory programmatic `definePack()` object in the same `LazyPackHandle` interface.
329
+ */
330
+ export function wrapEagerPackAsLazyHandle(pack) {
331
+ if (pack?.__lazyPackHandle) return pack;
332
+ const validated = pack?.__dislopPack ? pack : definePack(pack);
333
+
334
+ const loadStats = {
335
+ scriptsLoaded: false,
336
+ promptsLoaded: false,
337
+ scriptFileCount: validated.check || validated.verifyFix ? 1 : 0,
338
+ promptFileCount: validated.resolvePrompt ? 1 : 0,
339
+ };
340
+
341
+ return Object.freeze({
342
+ __dislopPack: true,
343
+ __lazyPackHandle: true,
344
+ name: validated.name,
345
+ version: validated.version,
346
+ description: validated.description,
347
+ languages: validated.languages,
348
+ formats: validated.formats,
349
+ modalities: validated.modalities,
350
+ appliesTo: validated.appliesTo || null,
351
+ hasScripts: Boolean(validated.check || validated.verifyFix),
352
+ hasPrompts: Boolean(validated.resolvePrompt),
353
+ loadStats,
354
+
355
+ async loadScripts() {
356
+ loadStats.scriptsLoaded = true;
357
+ if (!validated.check && !validated.verifyFix && !validated.appliesTo) return [];
358
+ return [
359
+ {
360
+ appliesTo: validated.appliesTo || null,
361
+ check: validated.check || null,
362
+ verifyFix: validated.verifyFix || null,
363
+ },
364
+ ];
365
+ },
366
+
367
+ async loadPrompts(doc, ctx) {
368
+ loadStats.promptsLoaded = true;
369
+ if (typeof validated.resolvePrompt !== "function") return [];
370
+ const res = validated.resolvePrompt(doc, ctx);
371
+ if (!res || !Array.isArray(res.rules)) return [];
372
+ return [{ roleHint: res.roleHint || "", rules: res.rules }];
373
+ },
374
+ });
375
+ }
376
+
377
+ function isSeparatedPackDirectory(dirPath) {
378
+ return fs.existsSync(path.join(dirPath, "pack.json"));
379
+ }
380
+
381
+ /**
382
+ * Enumerate all built-in Packs under `packs/<scope-or-lang>/<scenario>/` by reading `pack.json` only.
383
+ */
384
+ export function listBuiltinPackIds(packsRoot = BUILTIN_PACKS_ROOT) {
385
+ if (!fs.existsSync(packsRoot)) return [];
386
+ const results = [];
387
+ for (const level1 of fs.readdirSync(packsRoot, { withFileTypes: true })) {
388
+ if (!level1.isDirectory()) continue;
389
+ const level1Dir = path.join(packsRoot, level1.name);
390
+ for (const level2 of fs.readdirSync(level1Dir, { withFileTypes: true })) {
391
+ if (!level2.isDirectory()) continue;
392
+ const packDir = path.join(level1Dir, level2.name);
393
+ if (
394
+ isSeparatedPackDirectory(packDir) ||
395
+ fs.existsSync(path.join(packDir, "index.mjs")) ||
396
+ fs.existsSync(path.join(packDir, "pack.md"))
397
+ ) {
398
+ results.push(`${level1.name}/${level2.name}`);
399
+ }
400
+ }
401
+ }
402
+ return results.sort();
403
+ }
404
+
405
+ async function loadFromFilesystemEntry(targetPath) {
406
+ const stat = fs.statSync(targetPath);
407
+ if (stat.isDirectory()) {
408
+ if (isSeparatedPackDirectory(targetPath)) {
409
+ return createDirectoryPackHandle(targetPath);
410
+ }
411
+ const candidates = ["index.mjs", "index.js", "pack.md"].map((f) => path.join(targetPath, f));
412
+ const found = candidates.find((p) => fs.existsSync(p));
413
+ if (!found) {
414
+ throw new Error(`Pack directory '${targetPath}' is missing pack.json, index.mjs, or pack.md`);
415
+ }
416
+ return loadFromFilesystemEntry(found);
417
+ }
418
+
419
+ if (/\.md$/i.test(targetPath)) {
420
+ return compileMarkdownPack(fs.readFileSync(targetPath, "utf8"), targetPath);
421
+ }
422
+ if (path.basename(targetPath) === "pack.json") {
423
+ return createDirectoryPackHandle(path.dirname(targetPath));
424
+ }
425
+
426
+ const mod = await import(pathToFileURL(targetPath).href);
427
+ const candidate = mod.default || mod.pack;
428
+ if (!candidate || typeof candidate !== "object") {
429
+ throw new Error(`Pack module '${targetPath}' does not export a default definePack() object`);
430
+ }
431
+ return wrapEagerPackAsLazyHandle(candidate);
432
+ }
433
+
434
+ /**
435
+ * Resolve a single Pack specifier into a `LazyPackHandle` WITHOUT importing `scripts/` or reading `prompts/`
436
+ * when the pack is a separated Pack directory (`pack.json`).
437
+ */
438
+ export async function loadSinglePack(
439
+ specifier,
440
+ {
441
+ docLanguage = "en",
442
+ cwd = process.cwd(),
443
+ packsRoot = BUILTIN_PACKS_ROOT,
444
+ packOrigin = "cli",
445
+ projectDir = null,
446
+ } = {},
447
+ ) {
448
+ if (specifier && typeof specifier === "object") {
449
+ return wrapEagerPackAsLazyHandle(specifier);
450
+ }
451
+ const raw = String(specifier || "").trim();
452
+ if (!raw) {
453
+ throw new Error("Empty Pack specifier");
454
+ }
455
+
456
+ const isUntrustedOrigin = packOrigin === "project" || packOrigin === "mcp";
457
+ const looksLikePath =
458
+ raw.startsWith("./") ||
459
+ raw.startsWith("../") ||
460
+ path.isAbsolute(raw) ||
461
+ /\.(?:mjs|js|cjs|md|json)$/i.test(raw);
462
+ if (looksLikePath) {
463
+ const baseDir = projectDir || cwd;
464
+ const abs = path.resolve(baseDir, raw);
465
+ if (!fs.existsSync(abs)) {
466
+ throw new Error(`Pack path not found: '${raw}' (resolved to '${abs}')`);
467
+ }
468
+ if (isUntrustedOrigin) {
469
+ const realBase = fs.realpathSync(baseDir);
470
+ const realTarget = fs.realpathSync(abs);
471
+ const rel = path.relative(realBase, realTarget);
472
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
473
+ throw new DislopConfigError(
474
+ `Pack path '${raw}' escapes project directory '${baseDir}' under untrusted origin '${packOrigin}'.`,
475
+ );
476
+ }
477
+ const stat = fs.statSync(realTarget);
478
+ if (stat.isFile() && !/\.md$/i.test(realTarget)) {
479
+ throw new DislopConfigError(
480
+ `Untrusted origin '${packOrigin}' cannot execute script pack '${raw}'. Only validated .pack.md files are permitted.`,
481
+ );
482
+ }
483
+ const validation = validatePackPath(realTarget, { cwd: baseDir });
484
+ if (!validation.ok) {
485
+ throw new DislopConfigError(
486
+ `Pack validation failed for '${raw}': ${validation.violations.map((v) => v.message).join("; ")}`,
487
+ );
488
+ }
489
+ const loaded = await loadFromFilesystemEntry(realTarget);
490
+ if (loaded.hasScripts) {
491
+ throw new DislopConfigError(
492
+ `Untrusted origin '${packOrigin}' cannot mount script-bearing pack '${raw}'.`,
493
+ );
494
+ }
495
+ return loaded;
496
+ }
497
+ return loadFromFilesystemEntry(abs);
498
+ }
499
+
500
+ let normalizedId = SHORTHAND_ALIASES[raw] || raw;
501
+ if (normalizedId.includes("\0") || normalizedId.includes("\\") || normalizedId.includes("..")) {
502
+ throw new DislopConfigError(`Invalid Pack identifier '${raw}'`);
503
+ }
504
+ if (!normalizedId.includes("/")) {
505
+ const langDir = path.join(packsRoot, docLanguage, normalizedId);
506
+ const commonDir = path.join(packsRoot, "common", normalizedId);
507
+ if (fs.existsSync(langDir)) {
508
+ normalizedId = `${docLanguage}/${normalizedId}`;
509
+ } else if (fs.existsSync(commonDir)) {
510
+ normalizedId = `common/${normalizedId}`;
511
+ }
512
+ }
513
+
514
+ const builtinIds = new Set(listBuiltinPackIds(packsRoot));
515
+ if (builtinIds.has(normalizedId)) {
516
+ const realPacksRoot = fs.realpathSync(packsRoot);
517
+ const builtinDir = path.join(realPacksRoot, ...normalizedId.split("/"));
518
+ if (fs.existsSync(builtinDir) && fs.statSync(builtinDir).isDirectory()) {
519
+ const realBuiltinDir = fs.realpathSync(builtinDir);
520
+ const rel = path.relative(realPacksRoot, realBuiltinDir);
521
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
522
+ throw new DislopConfigError(`Built-in pack '${normalizedId}' escapes packs root`);
523
+ }
524
+ return loadFromFilesystemEntry(realBuiltinDir);
525
+ }
526
+ }
527
+
528
+ if (isUntrustedOrigin) {
529
+ throw new DislopConfigError(
530
+ `Untrusted origin '${packOrigin}' cannot resolve external npm pack '${raw}'. Built-in packs: ${listBuiltinPackIds(packsRoot).join(", ")}`,
531
+ );
532
+ }
533
+
534
+ // Installed npm package fallback
535
+ try {
536
+ const req = createRequire(path.join(cwd, "package.json"));
537
+ const pkgEntry = req.resolve(raw);
538
+ const pkgDir = path.dirname(pkgEntry);
539
+ if (isSeparatedPackDirectory(pkgDir)) {
540
+ return createDirectoryPackHandle(pkgDir);
541
+ }
542
+ return loadFromFilesystemEntry(pkgEntry);
543
+ } catch {
544
+ throw new Error(
545
+ `Unknown Pack '${raw}'. Built-in packs: ${listBuiltinPackIds(packsRoot).join(", ")}`,
546
+ );
547
+ }
548
+ }
549
+
550
+ function builtinPackExists(packsRoot, id) {
551
+ const dir = path.join(packsRoot, ...id.split("/"));
552
+ return (
553
+ isSeparatedPackDirectory(dir) ||
554
+ fs.existsSync(path.join(dir, "index.mjs")) ||
555
+ fs.existsSync(path.join(dir, "pack.md"))
556
+ );
557
+ }
558
+
559
+ /**
560
+ * Determine default Pack specifiers for a `DocumentModel` when no custom `--pack` was given.
561
+ */
562
+ export function defaultPackSpecifiersForDoc(doc, packsRoot = BUILTIN_PACKS_ROOT) {
563
+ const lang = doc.language === "zh" ? "zh" : "en";
564
+ const specs = ["common/artifact-qa"];
565
+
566
+ const pushIfBuiltinExists = (id) => {
567
+ if (builtinPackExists(packsRoot, id)) specs.push(id);
568
+ };
569
+
570
+ if (doc.segments.length > 0) {
571
+ pushIfBuiltinExists(`${lang}/artifact-qa`);
572
+ }
573
+
574
+ if (["html", "css", "jsx", "tsx", "svg"].includes(doc.format)) {
575
+ specs.push("common/web-ui");
576
+ if (doc.segments.length > 0) {
577
+ pushIfBuiltinExists(`${lang}/web-ui`);
578
+ }
579
+ }
580
+
581
+ if (["pptx", "pdf", "png", "jpg", "jpeg", "webp", "gif"].includes(doc.format)) {
582
+ specs.push("common/slide-deck");
583
+ if (doc.segments.length > 0) {
584
+ pushIfBuiltinExists(`${lang}/slide-deck`);
585
+ }
586
+ }
587
+
588
+ if (doc.segments.length > 0) {
589
+ pushIfBuiltinExists(`${lang}/prose`);
590
+ }
591
+
592
+ return specs;
593
+ }
594
+
595
+ function expandScenarioShorthands(rawSpecs, docLanguage, packsRoot, defaultOrigin = "cli") {
596
+ const expanded = [];
597
+ for (const entry of rawSpecs) {
598
+ const isWrapped = entry && typeof entry === "object" && typeof entry.spec === "string";
599
+ const specVal = isWrapped ? entry.spec : entry;
600
+ const itemOrigin = isWrapped && entry.origin ? entry.origin : defaultOrigin;
601
+
602
+ if (typeof specVal !== "string") {
603
+ expanded.push({ spec: specVal, origin: itemOrigin });
604
+ continue;
605
+ }
606
+ const trimmed = specVal.trim();
607
+ const looksLikePath =
608
+ trimmed.startsWith("./") ||
609
+ trimmed.startsWith("../") ||
610
+ path.isAbsolute(trimmed) ||
611
+ /\.(?:mjs|js|cjs|md|json)$/i.test(trimmed);
612
+
613
+ if (looksLikePath || trimmed.includes("/") || SHORTHAND_ALIASES[trimmed]) {
614
+ expanded.push({ spec: trimmed, origin: itemOrigin });
615
+ continue;
616
+ }
617
+
618
+ const commonId = `common/${trimmed}`;
619
+ const langId = `${docLanguage}/${trimmed}`;
620
+ const hasCommon = builtinPackExists(packsRoot, commonId);
621
+ const hasLang = builtinPackExists(packsRoot, langId);
622
+
623
+ if (hasCommon && hasLang) {
624
+ expanded.push({ spec: commonId, origin: itemOrigin }, { spec: langId, origin: itemOrigin });
625
+ } else {
626
+ expanded.push({ spec: trimmed, origin: itemOrigin });
627
+ }
628
+ }
629
+ return expanded;
630
+ }
631
+
632
+ export function packMetadataAppliesToDoc(pack, doc) {
633
+ if (pack.languages && pack.languages.length > 0 && !pack.languages.includes(doc.language)) {
634
+ return false;
635
+ }
636
+ if (pack.formats && pack.formats.length > 0 && !pack.formats.includes(doc.format)) {
637
+ return false;
638
+ }
639
+ if (pack.modalities && pack.modalities.length > 0 && !pack.modalities.includes(doc.modality)) {
640
+ return false;
641
+ }
642
+ if (typeof pack.appliesTo === "function") {
643
+ return Boolean(pack.appliesTo(doc));
644
+ }
645
+ return true;
646
+ }
647
+
648
+ /**
649
+ * Resolve and filter active Packs for `doc` using `pack.json` metadata ONLY
650
+ * (zero `scripts/` imports and zero `prompts/` reads during admission!).
651
+ */
652
+ export async function resolveActivePacks(
653
+ doc,
654
+ {
655
+ packSpecifiers = null,
656
+ extraPackSpecifiers = null,
657
+ cwd = process.cwd(),
658
+ packsRoot = BUILTIN_PACKS_ROOT,
659
+ packOrigin = "cli",
660
+ projectDir = null,
661
+ } = {},
662
+ ) {
663
+ let requested =
664
+ packSpecifiers && packSpecifiers.length > 0
665
+ ? expandScenarioShorthands(packSpecifiers, doc.language, packsRoot, packOrigin)
666
+ : defaultPackSpecifiersForDoc(doc, packsRoot).map((spec) => ({ spec, origin: "default" }));
667
+
668
+ if (packOrigin !== "cli" && packSpecifiers && packSpecifiers.length > 0) {
669
+ if (!requested.some((r) => r.spec === "common/artifact-qa")) {
670
+ requested = [{ spec: "common/artifact-qa", origin: "default" }, ...requested];
671
+ }
672
+ }
673
+ if (extraPackSpecifiers && extraPackSpecifiers.length > 0) {
674
+ requested = [
675
+ ...requested,
676
+ ...expandScenarioShorthands(extraPackSpecifiers, doc.language, packsRoot, packOrigin),
677
+ ];
678
+ }
679
+
680
+ const loaded = [];
681
+ const seenNames = new Set();
682
+ for (const item of requested) {
683
+ const pack = await loadSinglePack(item.spec, {
684
+ docLanguage: doc.language,
685
+ cwd,
686
+ packsRoot,
687
+ packOrigin: item.origin,
688
+ projectDir,
689
+ });
690
+ if (seenNames.has(pack.name)) continue;
691
+ seenNames.add(pack.name);
692
+ if (packMetadataAppliesToDoc(pack, doc)) {
693
+ loaded.push(pack);
694
+ }
695
+ }
696
+ return loaded;
697
+ }
698
+
699
+ export function qualifyRuleId(packName, ruleId) {
700
+ const cleanRule = String(ruleId || "rule").trim();
701
+ if (cleanRule.startsWith(`${packName}/`)) return cleanRule;
702
+ return `${packName}/${cleanRule}`;
703
+ }
704
+
705
+ /**
706
+ * Lazily import `scripts/` ONLY for admitted Packs that declare `hasScripts`,
707
+ * and execute `check(doc, ctx)` in parallel. Never touches `prompts/`.
708
+ */
709
+ export async function runDeterministicPackChecks(
710
+ doc,
711
+ activePacks,
712
+ { diagnosticLang = doc.language, cwd = process.cwd() } = {},
713
+ ) {
714
+ const items = [];
715
+
716
+ await Promise.all(
717
+ activePacks.map(async (pack) => {
718
+ if (!pack.hasScripts) return;
719
+ const scriptModules = await pack.loadScripts();
720
+ if (scriptModules.length === 0) return;
721
+
722
+ const localItems = [];
723
+ const ctx = Object.freeze({
724
+ diagnosticLang,
725
+ cwd,
726
+ reportDefect(input) {
727
+ if (!input || typeof input !== "object") return;
728
+ const severity = VALID_DEFECT_SEVERITIES.includes(input.severity) ? input.severity : "error";
729
+ const fixSafety = VALID_FIX_SAFETIES.includes(input.fixSafety) ? input.fixSafety : "manual";
730
+ const suggestedReplacement = String(input.suggestedReplacement ?? "");
731
+ const actionType = VALID_ACTION_TYPES.includes(input.actionType)
732
+ ? input.actionType
733
+ : fixSafety !== "manual" && suggestedReplacement === ""
734
+ ? "delete"
735
+ : suggestedReplacement
736
+ ? "replace"
737
+ : "prompt";
738
+
739
+ const seg = input.targetId ? doc.segments.find((s) => s.id === input.targetId) : null;
740
+ localItems.push({
741
+ kind: "defect",
742
+ pack: pack.name,
743
+ ruleId: qualifyRuleId(pack.name, input.ruleId),
744
+ targetId: input.targetId || null,
745
+ ...(input.line ?? seg?.line ? { line: input.line ?? seg?.line } : {}),
746
+ severity,
747
+ fixSafety,
748
+ actionType,
749
+ originalQuote: String(input.originalQuote ?? seg?.text ?? ""),
750
+ suggestedReplacement,
751
+ reason: String(input.reason || "Objective artifact defect."),
752
+ ...(input.rewritePrompt ? { rewritePrompt: String(input.rewritePrompt) } : {}),
753
+ ...(input.locator ? { _locator: input.locator } : {}),
754
+ });
755
+ },
756
+ reportSuggestion(input) {
757
+ if (!input || typeof input !== "object") return;
758
+ const priority = VALID_SUGGESTION_PRIORITIES.includes(input.priority)
759
+ ? input.priority
760
+ : "moderate";
761
+ const fixSafety = VALID_FIX_SAFETIES.includes(input.fixSafety) ? input.fixSafety : "review";
762
+ const suggestedReplacement = String(input.suggestedReplacement ?? "");
763
+ const actionType = VALID_ACTION_TYPES.includes(input.actionType)
764
+ ? input.actionType
765
+ : fixSafety !== "manual" && suggestedReplacement === ""
766
+ ? "delete"
767
+ : suggestedReplacement
768
+ ? "replace"
769
+ : "prompt";
770
+
771
+ const seg = input.targetId ? doc.segments.find((s) => s.id === input.targetId) : null;
772
+ localItems.push({
773
+ kind: "suggestion",
774
+ pack: pack.name,
775
+ ruleId: qualifyRuleId(pack.name, input.ruleId),
776
+ targetId: input.targetId || null,
777
+ ...(input.line ?? seg?.line ? { line: input.line ?? seg?.line } : {}),
778
+ priority,
779
+ fixSafety,
780
+ actionType,
781
+ originalQuote: String(input.originalQuote ?? seg?.text ?? ""),
782
+ suggestedReplacement,
783
+ reason: String(input.reason || "Editorial improvement suggestion."),
784
+ ...(input.rewritePrompt ? { rewritePrompt: String(input.rewritePrompt) } : {}),
785
+ ...(input.locator ? { _locator: input.locator } : {}),
786
+ });
787
+ },
788
+ });
789
+
790
+ for (const sm of scriptModules) {
791
+ if (typeof sm.appliesTo === "function" && !sm.appliesTo(doc)) continue;
792
+ if (typeof sm.check === "function") {
793
+ await sm.check(doc, ctx);
794
+ }
795
+ }
796
+ items.push(...localItems);
797
+ }),
798
+ );
799
+
800
+ return items;
801
+ }