dislop 1.0.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 (52) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.cursor-plugin/plugin.json +1 -1
  5. package/PRODUCT.md +2 -2
  6. package/README.md +34 -33
  7. package/README.zh-CN.md +65 -61
  8. package/gemini-extension.json +1 -1
  9. package/package.json +2 -2
  10. package/packs/common/artifact-qa/scripts/index.mjs +64 -2
  11. package/packs/en/artifact-qa/scripts/index.mjs +1 -1
  12. package/packs/en/prose/scripts/index.mjs +3 -0
  13. package/plugin.json +1 -1
  14. package/server.json +2 -2
  15. package/skills/dislop/SKILL.md +1 -1
  16. package/skills/dislop/agents/openai.yaml +1 -1
  17. package/skills/dislop/references/essay.md +5 -5
  18. package/skills/dislop/references/essay.zh-CN.md +5 -5
  19. package/skills/dislop/references/office.md +4 -4
  20. package/skills/dislop/references/office.zh-CN.md +4 -4
  21. package/skills/dislop/references/web-ui.md +3 -3
  22. package/skills/dislop/references/web-ui.zh-CN.md +3 -3
  23. package/skills/dislop/references/work-docs.md +6 -6
  24. package/skills/dislop/references/work-docs.zh-CN.md +6 -6
  25. package/src/cli-main.mjs +88 -6
  26. package/src/commands/check-fix.mjs +170 -15
  27. package/src/commands/doctor.mjs +23 -1
  28. package/src/commands/init.mjs +24 -18
  29. package/src/commands/packs.mjs +41 -4
  30. package/src/commands/verify.mjs +36 -4
  31. package/src/commands/voice.mjs +1 -1
  32. package/src/commands/worklog.mjs +424 -0
  33. package/src/kernel/config.mjs +546 -19
  34. package/src/kernel/document-model.mjs +30 -10
  35. package/src/kernel/fact-gate.mjs +160 -0
  36. package/src/kernel/file-discovery.mjs +168 -11
  37. package/src/kernel/ooxml-binary.mjs +86 -0
  38. package/src/kernel/pack-loader.mjs +107 -21
  39. package/src/kernel/pack-validator.mjs +491 -0
  40. package/src/kernel/patcher.mjs +177 -47
  41. package/src/kernel/pipeline.mjs +284 -21
  42. package/src/kernel/prompt-assembler.mjs +37 -8
  43. package/src/kernel/version.mjs +7 -0
  44. package/src/kernel/voice-profile.mjs +3 -0
  45. package/src/mcp/stdio-server.mjs +71 -1
  46. package/src/runners/auto-fix.mjs +17 -2
  47. package/src/runners/interactive-tty.mjs +32 -5
  48. package/src/runners/reporters.mjs +18 -2
  49. package/src/runtime/providers/cloud.mjs +4 -2
  50. package/src/runtime/providers/local-model.mjs +8 -0
  51. package/src/runtime/router.mjs +11 -2
  52. package/src/runtime/worklog.mjs +904 -0
@@ -2,6 +2,8 @@ import fs from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { DislopConfigError } from "./config.mjs";
6
+ import { validatePackPath } from "./pack-validator.mjs";
5
7
  import {
6
8
  VALID_ACTION_TYPES,
7
9
  VALID_DEFECT_SEVERITIES,
@@ -435,7 +437,13 @@ async function loadFromFilesystemEntry(targetPath) {
435
437
  */
436
438
  export async function loadSinglePack(
437
439
  specifier,
438
- { docLanguage = "en", cwd = process.cwd(), packsRoot = BUILTIN_PACKS_ROOT } = {},
440
+ {
441
+ docLanguage = "en",
442
+ cwd = process.cwd(),
443
+ packsRoot = BUILTIN_PACKS_ROOT,
444
+ packOrigin = "cli",
445
+ projectDir = null,
446
+ } = {},
439
447
  ) {
440
448
  if (specifier && typeof specifier === "object") {
441
449
  return wrapEagerPackAsLazyHandle(specifier);
@@ -445,20 +453,54 @@ export async function loadSinglePack(
445
453
  throw new Error("Empty Pack specifier");
446
454
  }
447
455
 
456
+ const isUntrustedOrigin = packOrigin === "project" || packOrigin === "mcp";
448
457
  const looksLikePath =
449
458
  raw.startsWith("./") ||
450
459
  raw.startsWith("../") ||
451
460
  path.isAbsolute(raw) ||
452
- /\.(?:mjs|js|md|json)$/i.test(raw);
461
+ /\.(?:mjs|js|cjs|md|json)$/i.test(raw);
453
462
  if (looksLikePath) {
454
- const abs = path.resolve(cwd, raw);
463
+ const baseDir = projectDir || cwd;
464
+ const abs = path.resolve(baseDir, raw);
455
465
  if (!fs.existsSync(abs)) {
456
466
  throw new Error(`Pack path not found: '${raw}' (resolved to '${abs}')`);
457
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
+ }
458
497
  return loadFromFilesystemEntry(abs);
459
498
  }
460
499
 
461
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
+ }
462
504
  if (!normalizedId.includes("/")) {
463
505
  const langDir = path.join(packsRoot, docLanguage, normalizedId);
464
506
  const commonDir = path.join(packsRoot, "common", normalizedId);
@@ -469,9 +511,24 @@ export async function loadSinglePack(
469
511
  }
470
512
  }
471
513
 
472
- const builtinDir = path.join(packsRoot, ...normalizedId.split("/"));
473
- if (fs.existsSync(builtinDir) && fs.statSync(builtinDir).isDirectory()) {
474
- return loadFromFilesystemEntry(builtinDir);
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
+ );
475
532
  }
476
533
 
477
534
  // Installed npm package fallback
@@ -535,22 +592,26 @@ export function defaultPackSpecifiersForDoc(doc, packsRoot = BUILTIN_PACKS_ROOT)
535
592
  return specs;
536
593
  }
537
594
 
538
- function expandScenarioShorthands(rawSpecs, docLanguage, packsRoot) {
595
+ function expandScenarioShorthands(rawSpecs, docLanguage, packsRoot, defaultOrigin = "cli") {
539
596
  const expanded = [];
540
- for (const spec of rawSpecs) {
541
- if (typeof spec !== "string") {
542
- expanded.push(spec);
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 });
543
604
  continue;
544
605
  }
545
- const trimmed = spec.trim();
606
+ const trimmed = specVal.trim();
546
607
  const looksLikePath =
547
608
  trimmed.startsWith("./") ||
548
609
  trimmed.startsWith("../") ||
549
610
  path.isAbsolute(trimmed) ||
550
- /\.(?:mjs|js|md|json)$/i.test(trimmed);
611
+ /\.(?:mjs|js|cjs|md|json)$/i.test(trimmed);
551
612
 
552
613
  if (looksLikePath || trimmed.includes("/") || SHORTHAND_ALIASES[trimmed]) {
553
- expanded.push(trimmed);
614
+ expanded.push({ spec: trimmed, origin: itemOrigin });
554
615
  continue;
555
616
  }
556
617
 
@@ -560,9 +621,9 @@ function expandScenarioShorthands(rawSpecs, docLanguage, packsRoot) {
560
621
  const hasLang = builtinPackExists(packsRoot, langId);
561
622
 
562
623
  if (hasCommon && hasLang) {
563
- expanded.push(commonId, langId);
624
+ expanded.push({ spec: commonId, origin: itemOrigin }, { spec: langId, origin: itemOrigin });
564
625
  } else {
565
- expanded.push(trimmed);
626
+ expanded.push({ spec: trimmed, origin: itemOrigin });
566
627
  }
567
628
  }
568
629
  return expanded;
@@ -590,17 +651,42 @@ export function packMetadataAppliesToDoc(pack, doc) {
590
651
  */
591
652
  export async function resolveActivePacks(
592
653
  doc,
593
- { packSpecifiers = null, cwd = process.cwd(), packsRoot = BUILTIN_PACKS_ROOT } = {},
654
+ {
655
+ packSpecifiers = null,
656
+ extraPackSpecifiers = null,
657
+ cwd = process.cwd(),
658
+ packsRoot = BUILTIN_PACKS_ROOT,
659
+ packOrigin = "cli",
660
+ projectDir = null,
661
+ } = {},
594
662
  ) {
595
- const requested =
663
+ let requested =
596
664
  packSpecifiers && packSpecifiers.length > 0
597
- ? expandScenarioShorthands(packSpecifiers, doc.language, packsRoot)
598
- : defaultPackSpecifiersForDoc(doc, packsRoot);
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
+ }
599
679
 
600
680
  const loaded = [];
601
681
  const seenNames = new Set();
602
- for (const spec of requested) {
603
- const pack = await loadSinglePack(spec, { docLanguage: doc.language, cwd, packsRoot });
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
+ });
604
690
  if (seenNames.has(pack.name)) continue;
605
691
  seenNames.add(pack.name);
606
692
  if (packMetadataAppliesToDoc(pack, doc)) {
@@ -0,0 +1,491 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export const PACK_ALLOWED_LANGUAGES = new Set(["en", "zh", "common", "multi", "any"]);
5
+ export const INVISIBLE_UNICODE_REGEX = /[\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]/;
6
+ export const CJK_CHAR_REGEX = /[\u4E00-\u9FFF]/;
7
+
8
+ const PROMPT_INJECTION_RULES = [
9
+ {
10
+ id: "prompt-injection/instruction-override",
11
+ regex: /\b(?:ignore|disregard|forget|bypass|override)\s+(?:all\s+|any\s+|your\s+)?(?:previous|prior|above|system|kernel|safety|security)\s+(?:instructions|prompts?|rules|invariants|policies|constraints)\b/i,
12
+ message: "Contains instruction-override / jailbreak phrasing",
13
+ },
14
+ {
15
+ id: "prompt-injection/role-hijack",
16
+ regex: /\b(?:you\s+are\s+now|new\s+system\s+prompt|act\s+as\s+unrestricted|developer\s+mode\s+enabled|jailbreak)\b/i,
17
+ message: "Contains role-hijack or jailbreak directive",
18
+ },
19
+ {
20
+ id: "prompt-injection/boundary-breakout",
21
+ regex: /<\/?(?:untrusted_document|context_readonly|pack_rules|established_tone_anchor|system)\b[^>]*>/i,
22
+ message: "Contains XML boundary tag breakout attempt",
23
+ },
24
+ {
25
+ id: "prompt-injection/suppression",
26
+ regex: /\b(?:always\s+report\s+zero\s+issues|report\s+zero\s+issues\s+for|suppress\s+all\s+(?:defects|errors|warnings)|always\s+return\s+(?:empty|clean))\b/i,
27
+ message: "Attempts to force false-negative clean results",
28
+ },
29
+ {
30
+ id: "prompt-injection/exfiltration",
31
+ regex: /\b(?:exfiltrate|leak\s+(?:secrets|tokens|env)|send\s+(?:all\s+)?(?:contents?|secrets?|tokens?|api[_ -]?keys?)\s+to\s+https?:|upload\s+.*\s+to\s+https?:)\b/i,
32
+ message: "Contains data-exfiltration or URL-redirect instruction",
33
+ },
34
+ {
35
+ id: "prompt-injection/url-swap",
36
+ regex: /\breplace\s+(?:all\s+)?(?:links?|urls?)\s+with\s+https?:\/\//i,
37
+ message: "Contains malicious URL replacement instruction",
38
+ },
39
+ {
40
+ id: "secret-leak/credential-literal",
41
+ regex: /\b(?:sk-[A-Za-z0-9_-]{20,}|AIza[0-9A-Za-z_-]{30,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
42
+ message: "Contains potential hardcoded API key or credential token",
43
+ },
44
+ ];
45
+
46
+ const SCRIPT_SECURITY_RULES = [
47
+ {
48
+ id: "script-security/forbidden-module",
49
+ regex: /(?:from\s+|import\s*\(\s*|require\s*\(\s*)["'](?:node:)?(?:child_process|fs\/promises|http|https|http2|net|tls|dgram|dns|vm|worker_threads|cluster|os|process|inspector|module|readline)["']/i,
50
+ message: "Imports restricted Node.js built-in module outside pack sandbox",
51
+ },
52
+ {
53
+ id: "script-security/fs-write",
54
+ regex: /\bfs\.(?:writeFile|appendFile|rm|unlink|mkdir|rmdir|rename|chmod|chown|copyFile|symlink|truncate)(?:Sync)?\s*\(/,
55
+ message: "Attempts destructive or mutating filesystem call inside pack script",
56
+ },
57
+ {
58
+ id: "script-security/dynamic-code-exec",
59
+ regex: /\b(?:eval\s*\(|new\s+Function\b|\bFunction\s*\(|import\s*\(|require\s*\()/,
60
+ message: "Uses dynamic code evaluation or dynamic module loading",
61
+ },
62
+ {
63
+ id: "script-security/network-access",
64
+ regex: /\b(?:fetch\s*\(|XMLHttpRequest|WebSocket|navigator\.sendBeacon)\b/,
65
+ message: "Attempts network access inside deterministic pack script",
66
+ },
67
+ {
68
+ id: "script-security/runtime-escape",
69
+ regex: /\b(?:process\.(?:env|exit|kill|binding|dlopen|mainModule|argv)|globalThis\s*\[|Reflect\.construct)\b/,
70
+ message: "Accesses restricted host runtime process or global state",
71
+ },
72
+ ];
73
+
74
+ function findLineNumber(text, index) {
75
+ if (index < 0) return 1;
76
+ return text.slice(0, index).split("\n").length;
77
+ }
78
+
79
+ /**
80
+ * Validate markdown prompt text or string fields for security and language purity.
81
+ */
82
+ export function validatePackPromptContent(content, filePath, { enforceEnglishOnly = false } = {}) {
83
+ const violations = [];
84
+ const text = String(content ?? "");
85
+
86
+ const invisibleMatch = INVISIBLE_UNICODE_REGEX.exec(text);
87
+ if (invisibleMatch) {
88
+ violations.push({
89
+ file: filePath,
90
+ ruleId: "pack-security/invisible-unicode",
91
+ severity: "error",
92
+ line: findLineNumber(text, invisibleMatch.index),
93
+ message: "Contains hidden zero-width or bidirectional control characters",
94
+ });
95
+ }
96
+
97
+ for (const rule of PROMPT_INJECTION_RULES) {
98
+ const match = rule.regex.exec(text);
99
+ if (match) {
100
+ violations.push({
101
+ file: filePath,
102
+ ruleId: rule.id,
103
+ severity: "error",
104
+ line: findLineNumber(text, match.index),
105
+ message: rule.message,
106
+ });
107
+ }
108
+ }
109
+
110
+ if (enforceEnglishOnly && CJK_CHAR_REGEX.test(text)) {
111
+ const match = CJK_CHAR_REGEX.exec(text);
112
+ violations.push({
113
+ file: filePath,
114
+ ruleId: "pack-hygiene/non-english-in-en-pack",
115
+ severity: "error",
116
+ line: findLineNumber(text, match ? match.index : 0),
117
+ message: "English or common pack must not contain literal CJK characters",
118
+ });
119
+ }
120
+
121
+ return violations;
122
+ }
123
+
124
+ /**
125
+ * Validate deterministic JS/MJS pack script content against dangerous host primitives.
126
+ */
127
+ export function validatePackScriptContent(
128
+ content,
129
+ filePath,
130
+ { enforceEnglishOnly = false, allowBuiltinFs = false } = {},
131
+ ) {
132
+ const violations = [];
133
+ const text = String(content ?? "");
134
+
135
+ const invisibleMatch = INVISIBLE_UNICODE_REGEX.exec(text);
136
+ if (invisibleMatch) {
137
+ violations.push({
138
+ file: filePath,
139
+ ruleId: "pack-security/invisible-unicode",
140
+ severity: "error",
141
+ line: findLineNumber(text, invisibleMatch.index),
142
+ message: "Script contains hidden zero-width or bidirectional control characters",
143
+ });
144
+ }
145
+
146
+ for (const rule of SCRIPT_SECURITY_RULES) {
147
+ const match = rule.regex.exec(text);
148
+ if (match) {
149
+ violations.push({
150
+ file: filePath,
151
+ ruleId: rule.id,
152
+ severity: "error",
153
+ line: findLineNumber(text, match.index),
154
+ message: rule.message,
155
+ });
156
+ }
157
+ }
158
+
159
+ // Flag external / parent-escaping ESM imports inside scripts
160
+ const allowedSpecs = new Set(["dislop/sdk"]);
161
+ if (allowBuiltinFs) {
162
+ allowedSpecs.add("node:fs");
163
+ allowedSpecs.add("node:path");
164
+ }
165
+ const importRegex = /(?:^|\n)\s*import\s+(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g;
166
+ let importMatch;
167
+ while ((importMatch = importRegex.exec(text)) !== null) {
168
+ const spec = importMatch[1];
169
+ if (!spec.startsWith("./") && !allowedSpecs.has(spec)) {
170
+ violations.push({
171
+ file: filePath,
172
+ ruleId: "script-security/external-import",
173
+ severity: "error",
174
+ line: findLineNumber(text, importMatch.index),
175
+ message: `Pack script import "${spec}" must be "dislop/sdk" or stay within local "./" pack files`,
176
+ });
177
+ }
178
+ }
179
+
180
+ if (enforceEnglishOnly && CJK_CHAR_REGEX.test(text)) {
181
+ const match = CJK_CHAR_REGEX.exec(text);
182
+ violations.push({
183
+ file: filePath,
184
+ ruleId: "pack-hygiene/non-english-in-en-pack",
185
+ severity: "error",
186
+ line: findLineNumber(text, match ? match.index : 0),
187
+ message: "English or common pack script must not contain literal CJK characters",
188
+ });
189
+ }
190
+
191
+ return violations;
192
+ }
193
+
194
+ function collectPackFiles(dirPath) {
195
+ const results = [];
196
+ const stack = [dirPath];
197
+ while (stack.length > 0) {
198
+ const current = stack.pop();
199
+ const entries = fs.readdirSync(current, { withFileTypes: true });
200
+ for (const entry of entries) {
201
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
202
+ const fullPath = path.join(current, entry.name);
203
+ if (entry.isDirectory()) {
204
+ stack.push(fullPath);
205
+ } else if (entry.isFile()) {
206
+ results.push(fullPath);
207
+ }
208
+ }
209
+ }
210
+ return results.sort();
211
+ }
212
+
213
+ function checkRelativePackRef(packDir, relPath, manifestPath, fieldName) {
214
+ const violations = [];
215
+ if (typeof relPath !== "string" || !relPath.trim()) {
216
+ violations.push({
217
+ file: manifestPath,
218
+ ruleId: "pack-manifest/invalid-path",
219
+ severity: "error",
220
+ message: `${fieldName} must be a non-empty relative path`,
221
+ });
222
+ return violations;
223
+ }
224
+ if (path.isAbsolute(relPath)) {
225
+ violations.push({
226
+ file: manifestPath,
227
+ ruleId: "pack-manifest/absolute-path",
228
+ severity: "error",
229
+ message: `${fieldName} must be relative, not absolute: ${relPath}`,
230
+ });
231
+ return violations;
232
+ }
233
+ const resolved = path.resolve(packDir, relPath);
234
+ const rel = path.relative(packDir, resolved);
235
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
236
+ violations.push({
237
+ file: manifestPath,
238
+ ruleId: "pack-manifest/path-traversal",
239
+ severity: "error",
240
+ message: `${fieldName} escapes pack directory: ${relPath}`,
241
+ });
242
+ return violations;
243
+ }
244
+ if (!fs.existsSync(resolved)) {
245
+ violations.push({
246
+ file: manifestPath,
247
+ ruleId: "pack-manifest/missing-ref",
248
+ severity: "error",
249
+ message: `${fieldName} references missing file: ${relPath}`,
250
+ });
251
+ }
252
+ return violations;
253
+ }
254
+
255
+ function validatePackDirectory(packDir, { enforceEnglishOnly = false, allowBuiltinFs = false } = {}) {
256
+ const violations = [];
257
+ const manifestPath = path.join(packDir, "pack.json");
258
+ let checkedFiles = 0;
259
+
260
+ if (!fs.existsSync(manifestPath)) {
261
+ violations.push({
262
+ file: manifestPath,
263
+ ruleId: "pack-manifest/missing",
264
+ severity: "error",
265
+ message: "Pack directory is missing required pack.json",
266
+ });
267
+ } else {
268
+ checkedFiles += 1;
269
+ let manifest;
270
+ const rawManifest = fs.readFileSync(manifestPath, "utf8");
271
+ violations.push(
272
+ ...validatePackPromptContent(rawManifest, manifestPath, { enforceEnglishOnly }),
273
+ );
274
+ try {
275
+ manifest = JSON.parse(rawManifest);
276
+ } catch (error) {
277
+ violations.push({
278
+ file: manifestPath,
279
+ ruleId: "pack-manifest/invalid-json",
280
+ severity: "error",
281
+ message: `Invalid pack.json JSON: ${error.message}`,
282
+ });
283
+ manifest = null;
284
+ }
285
+
286
+ if (manifest && typeof manifest === "object" && !Array.isArray(manifest)) {
287
+ const packId = manifest.name || manifest.id;
288
+ if (typeof packId !== "string" || !packId.trim()) {
289
+ violations.push({
290
+ file: manifestPath,
291
+ ruleId: "pack-manifest/missing-id",
292
+ severity: "error",
293
+ message: "pack.json must declare a non-empty string 'name' or 'id'",
294
+ });
295
+ }
296
+ if (manifest.language !== undefined) {
297
+ const langs = Array.isArray(manifest.language) ? manifest.language : [manifest.language];
298
+ for (const lang of langs) {
299
+ if (typeof lang !== "string" || !PACK_ALLOWED_LANGUAGES.has(lang)) {
300
+ violations.push({
301
+ file: manifestPath,
302
+ ruleId: "pack-manifest/invalid-language",
303
+ severity: "error",
304
+ message: `Unsupported pack language "${lang}"`,
305
+ });
306
+ }
307
+ }
308
+ }
309
+ if (typeof manifest.scripts === "string") {
310
+ violations.push(
311
+ ...checkRelativePackRef(packDir, manifest.scripts, manifestPath, "scripts"),
312
+ );
313
+ } else if (Array.isArray(manifest.scripts)) {
314
+ for (const entry of manifest.scripts) {
315
+ violations.push(...checkRelativePackRef(packDir, entry, manifestPath, "scripts"));
316
+ }
317
+ }
318
+ if (typeof manifest.prompts === "string") {
319
+ violations.push(
320
+ ...checkRelativePackRef(packDir, manifest.prompts, manifestPath, "prompts"),
321
+ );
322
+ } else if (Array.isArray(manifest.prompts)) {
323
+ for (const entry of manifest.prompts) {
324
+ const ref = typeof entry === "string" ? entry : entry?.path || entry?.file;
325
+ if (ref) {
326
+ violations.push(...checkRelativePackRef(packDir, ref, manifestPath, "prompts"));
327
+ }
328
+ }
329
+ }
330
+ } else if (manifest !== null) {
331
+ violations.push({
332
+ file: manifestPath,
333
+ ruleId: "pack-manifest/not-object",
334
+ severity: "error",
335
+ message: "pack.json root must be a JSON object",
336
+ });
337
+ }
338
+ }
339
+
340
+ const files = collectPackFiles(packDir);
341
+ for (const file of files) {
342
+ if (file === manifestPath) continue;
343
+ const ext = path.extname(file).toLowerCase();
344
+ if ([".mjs", ".js", ".cjs"].includes(ext)) {
345
+ checkedFiles += 1;
346
+ const content = fs.readFileSync(file, "utf8");
347
+ violations.push(
348
+ ...validatePackScriptContent(content, file, { enforceEnglishOnly, allowBuiltinFs }),
349
+ );
350
+ } else if ([".md", ".txt", ".json"].includes(ext)) {
351
+ checkedFiles += 1;
352
+ const content = fs.readFileSync(file, "utf8");
353
+ violations.push(...validatePackPromptContent(content, file, { enforceEnglishOnly }));
354
+ }
355
+ }
356
+
357
+ return {
358
+ exists: true,
359
+ ok: violations.length === 0,
360
+ kind: "dir",
361
+ targetPath: packDir,
362
+ checkedFiles,
363
+ violations,
364
+ };
365
+ }
366
+
367
+ function validatePackFile(filePath, { enforceEnglishOnly = false } = {}) {
368
+ const ext = path.extname(filePath).toLowerCase();
369
+ const base = path.basename(filePath).toLowerCase();
370
+ const content = fs.readFileSync(filePath, "utf8");
371
+ const violations = [];
372
+
373
+ if ([".mjs", ".js", ".cjs"].includes(ext)) {
374
+ violations.push(...validatePackScriptContent(content, filePath, { enforceEnglishOnly }));
375
+ } else if (base.endsWith(".pack.md") || base === "pack.md") {
376
+ violations.push(...validatePackPromptContent(content, filePath, { enforceEnglishOnly }));
377
+ if (!/^---\r?\n[\s\S]*?\r?\n---/.test(content)) {
378
+ violations.push({
379
+ file: filePath,
380
+ ruleId: "pack-markdown/missing-frontmatter",
381
+ severity: "error",
382
+ line: 1,
383
+ message: "Markdown pack file must begin with YAML frontmatter ('--- ... ---')",
384
+ });
385
+ }
386
+ const stripped = content.replace(/^---[\s\S]*?---\s*/, "").trim();
387
+ if (!stripped) {
388
+ violations.push({
389
+ file: filePath,
390
+ ruleId: "pack-markdown/empty",
391
+ severity: "error",
392
+ message: "Markdown pack file contains no rule instructions",
393
+ });
394
+ }
395
+ } else {
396
+ violations.push({
397
+ file: filePath,
398
+ ruleId: "pack-target/unsupported-file",
399
+ severity: "error",
400
+ message: `Unsupported pack file '${path.basename(filePath)}' (expected pack directory or *.pack.md)`,
401
+ });
402
+ }
403
+
404
+ return {
405
+ exists: true,
406
+ ok: violations.length === 0,
407
+ kind: "file",
408
+ targetPath: filePath,
409
+ checkedFiles: 1,
410
+ violations,
411
+ };
412
+ }
413
+
414
+ /**
415
+ * Validate a single pack directory or `.pack.md`/script file.
416
+ */
417
+ export function validatePackPath(targetPath, { cwd = process.cwd(), enforceEnglishOnly } = {}) {
418
+ const resolved = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
419
+ if (!fs.existsSync(resolved)) {
420
+ return {
421
+ exists: false,
422
+ ok: false,
423
+ kind: "missing",
424
+ targetPath: resolved,
425
+ checkedFiles: 0,
426
+ violations: [
427
+ {
428
+ file: resolved,
429
+ ruleId: "pack-target/missing",
430
+ severity: "error",
431
+ message: `Pack path does not exist: ${targetPath}`,
432
+ },
433
+ ],
434
+ };
435
+ }
436
+
437
+ const stat = fs.statSync(resolved);
438
+ const autoEnglishOnly =
439
+ enforceEnglishOnly !== undefined
440
+ ? enforceEnglishOnly
441
+ : /[\\/]packs[\\/](?:en|common)(?:[\\/]|$)/.test(resolved);
442
+
443
+ if (stat.isDirectory()) {
444
+ return validatePackDirectory(resolved, { enforceEnglishOnly: autoEnglishOnly });
445
+ }
446
+ return validatePackFile(resolved, { enforceEnglishOnly: autoEnglishOnly });
447
+ }
448
+
449
+ /**
450
+ * Validate all built-in packs under `packs/<lang>/<scenario>`.
451
+ */
452
+ export function validateBuiltinPacks(packsRoot) {
453
+ const packDirs = [];
454
+ if (fs.existsSync(packsRoot)) {
455
+ for (const langEntry of fs.readdirSync(packsRoot, { withFileTypes: true })) {
456
+ if (!langEntry.isDirectory()) continue;
457
+ const langDir = path.join(packsRoot, langEntry.name);
458
+ for (const scenarioEntry of fs.readdirSync(langDir, { withFileTypes: true })) {
459
+ if (!scenarioEntry.isDirectory()) continue;
460
+ packDirs.push({
461
+ id: `${langEntry.name}/${scenarioEntry.name}`,
462
+ lang: langEntry.name,
463
+ dir: path.join(langDir, scenarioEntry.name),
464
+ });
465
+ }
466
+ }
467
+ }
468
+ packDirs.sort((a, b) => a.id.localeCompare(b.id));
469
+
470
+ const results = [];
471
+ const violations = [];
472
+ let checkedFiles = 0;
473
+
474
+ for (const entry of packDirs) {
475
+ const res = validatePackDirectory(entry.dir, {
476
+ enforceEnglishOnly: entry.lang === "en" || entry.lang === "common",
477
+ allowBuiltinFs: true,
478
+ });
479
+ results.push({ id: entry.id, ...res });
480
+ checkedFiles += res.checkedFiles;
481
+ violations.push(...res.violations);
482
+ }
483
+
484
+ return {
485
+ ok: violations.length === 0,
486
+ packCount: results.length,
487
+ checkedFiles,
488
+ results,
489
+ violations,
490
+ };
491
+ }