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,759 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ export class DislopConfigError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "DislopConfigError";
11
+ this.exitCode = 2;
12
+ }
13
+ }
14
+
15
+ export function getDislopHomeDir(env = process.env) {
16
+ if (env.DISLOP_CONFIG_DIR) {
17
+ return path.resolve(env.DISLOP_CONFIG_DIR);
18
+ }
19
+ const xdg = env.XDG_CONFIG_HOME;
20
+ if (xdg) {
21
+ return path.join(xdg, "dislop");
22
+ }
23
+ return path.join(os.homedir(), ".config", "dislop");
24
+ }
25
+
26
+ export function expandTilde(filePath, env = process.env) {
27
+ const s = String(filePath || "");
28
+ if (s === "~") return env.HOME || os.homedir();
29
+ if (s.startsWith("~/") || s.startsWith("~\\")) {
30
+ return path.join(env.HOME || os.homedir(), s.slice(2));
31
+ }
32
+ return s;
33
+ }
34
+
35
+ /**
36
+ * Detect whether the current process is attached to an interactive human terminal
37
+ * (false in pipes, CI runners, `TERM=dumb`, and known coding agent sandboxes).
38
+ */
39
+ export function isInteractiveHumanTty({
40
+ stdin = process.stdin,
41
+ stdout = process.stdout,
42
+ env = process.env,
43
+ } = {}) {
44
+ if (env.DISLOP_FORCE_TTY === "1") return true;
45
+ if (env.DISLOP_FORCE_NON_TTY === "1") return false;
46
+ if (!stdin?.isTTY || !stdout?.isTTY) return false;
47
+ if (env.CI && env.CI !== "0" && env.CI !== "false") return false;
48
+ if (env.TERM === "dumb") return false;
49
+ if (
50
+ env.CLAUDECODE ||
51
+ env.CODEX_SANDBOX ||
52
+ env.CURSOR_AGENT ||
53
+ env.ANTIGRAVITY_AGENT ||
54
+ env.GITHUB_ACTIONS
55
+ ) {
56
+ return false;
57
+ }
58
+ return true;
59
+ }
60
+
61
+ export function readJsonFileStrict(filePath) {
62
+ if (!fs.existsSync(filePath)) return null;
63
+ let raw;
64
+ try {
65
+ raw = fs.readFileSync(filePath, "utf8");
66
+ } catch (err) {
67
+ throw new DislopConfigError(`Unable to read config file '${filePath}': ${err.message}`);
68
+ }
69
+ try {
70
+ const parsed = JSON.parse(raw);
71
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
72
+ throw new Error("root value must be a JSON object");
73
+ }
74
+ return parsed;
75
+ } catch (err) {
76
+ throw new DislopConfigError(`Invalid JSON in '${filePath}': ${err.message}`);
77
+ }
78
+ }
79
+
80
+ export function writeJsonFileSecure(filePath, data, { mode = 0o600 } = {}) {
81
+ const dir = path.dirname(filePath);
82
+ fs.mkdirSync(dir, { recursive: true });
83
+ const tmp = path.join(dir, `.tmp-${process.pid}-${crypto.randomBytes(4).toString("hex")}`);
84
+ fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { encoding: "utf8", mode });
85
+ fs.renameSync(tmp, filePath);
86
+ }
87
+
88
+ const VALID_ROUTING_MODES = new Set(["off", "local", "auto", "cloud", "byok"]);
89
+ const VALID_PROJECT_ROUTING_MODES = new Set(["off", "local"]);
90
+ const VALID_WORKLOG_PRIVACY_MODES = new Set(["metadata", "redacted", "local-full"]);
91
+ const VALID_FAIL_ON_MODES = new Set(["none", "error", "warning"]);
92
+ const VALID_RULE_SEVERITIES = new Set(["off", "error", "warning", "strong", "moderate", "hint"]);
93
+
94
+ const PROJECT_ALLOWED_KEYS = new Set([
95
+ "$schema",
96
+ "routing",
97
+ "ignore",
98
+ "packs",
99
+ "extraPacks",
100
+ "overrides",
101
+ "rules",
102
+ "lang",
103
+ "level",
104
+ "concurrency",
105
+ "failOn",
106
+ "voice",
107
+ ]);
108
+
109
+ const PROJECT_PRIVILEGED_KEYS = new Set([
110
+ "providers",
111
+ "activeProvider",
112
+ "approvedHosts",
113
+ "worklog",
114
+ "credentialsPath",
115
+ "modelsDir",
116
+ ]);
117
+
118
+ function isPathInsideDir(targetPath, baseDir) {
119
+ const realBase = fs.existsSync(baseDir) ? fs.realpathSync(baseDir) : path.resolve(baseDir);
120
+ const candidate = fs.existsSync(targetPath)
121
+ ? fs.realpathSync(targetPath)
122
+ : path.resolve(targetPath);
123
+ const rel = path.relative(realBase, candidate);
124
+ return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
125
+ }
126
+
127
+ function findProjectRootAndConfigs(cwd) {
128
+ const startDir = path.resolve(cwd);
129
+ let gitBoundary = null;
130
+ let probe = startDir;
131
+ while (true) {
132
+ if (fs.existsSync(path.join(probe, ".git"))) {
133
+ gitBoundary = probe;
134
+ break;
135
+ }
136
+ const parent = path.dirname(probe);
137
+ if (parent === probe) break;
138
+ probe = parent;
139
+ }
140
+
141
+ const stopDir = gitBoundary || startDir;
142
+ let projectConfigPath = null;
143
+ let projectDir = stopDir;
144
+ probe = startDir;
145
+ while (true) {
146
+ const candidate = path.join(probe, ".dislop.json");
147
+ if (fs.existsSync(candidate)) {
148
+ projectConfigPath = candidate;
149
+ projectDir = probe;
150
+ break;
151
+ }
152
+ if (probe === stopDir) break;
153
+ const parent = path.dirname(probe);
154
+ if (parent === probe) break;
155
+ probe = parent;
156
+ }
157
+
158
+ const localConfigInProject = path.join(projectDir, ".dislop.local.json");
159
+ const localConfigInCwd = path.join(startDir, ".dislop.local.json");
160
+ const localConfigPath = fs.existsSync(localConfigInCwd)
161
+ ? localConfigInCwd
162
+ : localConfigInProject;
163
+
164
+ return {
165
+ projectDir,
166
+ gitBoundary,
167
+ projectConfigPath: projectConfigPath || path.join(projectDir, ".dislop.json"),
168
+ localConfigPath,
169
+ };
170
+ }
171
+
172
+ function isLocalConfigTrustedUntracked(localConfigPath, gitBoundary) {
173
+ if (!gitBoundary || !fs.existsSync(localConfigPath)) return true;
174
+ const res = spawnSync("git", ["ls-files", "--error-unmatch", localConfigPath], {
175
+ cwd: gitBoundary,
176
+ stdio: "ignore",
177
+ });
178
+ if (res.status === 0) {
179
+ // Exit 0 means `.dislop.local.json` is tracked in git -> untrusted escalation vector (R4)
180
+ throw new DislopConfigError(
181
+ `Security error: '${localConfigPath}' is tracked by git. Remove it from git index (.gitignore) or move shared settings into '.dislop.json'.`,
182
+ );
183
+ }
184
+ if (res.error || res.status !== 1) {
185
+ // Fail closed if git check failed or errored: downgrade `.dislop.local.json` to untrusted
186
+ return false;
187
+ }
188
+ return true;
189
+ }
190
+
191
+ export function normalizeFailOnValue(raw, label = "failOn") {
192
+ const val = String(raw || "").trim().toLowerCase();
193
+ if (val === "info" || val === "suggestion" || val === "strong" || val === "moderate" || val === "hint") {
194
+ throw new DislopConfigError(
195
+ `Invalid ${label} '${raw}': Suggestions cannot fail CI (Exit 0 invariant). Expected 'none', 'error', or 'warning'.`,
196
+ );
197
+ }
198
+ if (!VALID_FAIL_ON_MODES.has(val)) {
199
+ throw new DislopConfigError(`Invalid ${label} '${raw}' (expected 'none', 'error', or 'warning')`);
200
+ }
201
+ return val;
202
+ }
203
+
204
+ function validateProjectLayerKeys(d, source) {
205
+ for (const key of Object.keys(d)) {
206
+ if (key === "pack") {
207
+ throw new DislopConfigError(
208
+ `Invalid config key 'pack' in '${source}'. Migrate to 'packs' (array) and remove singular 'pack'.`,
209
+ );
210
+ }
211
+ if (PROJECT_PRIVILEGED_KEYS.has(key)) {
212
+ throw new DislopConfigError(
213
+ `Config key '${key}' is not permitted in shared project '${source}'. Place credentials/providers/worklog settings in user config (~/.config/dislop/config.json) or untracked '.dislop.local.json'.`,
214
+ );
215
+ }
216
+ if (!PROJECT_ALLOWED_KEYS.has(key)) {
217
+ throw new DislopConfigError(`Unknown config key '${key}' in '${source}'.`);
218
+ }
219
+ }
220
+ }
221
+
222
+ function validateRuleConfigValue(ruleId, rawVal, source) {
223
+ if (rawVal === false || rawVal === "off") return "off";
224
+ if (rawVal === true) return "on";
225
+ if (typeof rawVal === "string") {
226
+ const val = rawVal.trim().toLowerCase();
227
+ if (!VALID_RULE_SEVERITIES.has(val)) {
228
+ throw new DislopConfigError(
229
+ `Invalid severity '${rawVal}' for rule '${ruleId}' in '${source}'`,
230
+ );
231
+ }
232
+ return val;
233
+ }
234
+ if (rawVal && typeof rawVal === "object" && !Array.isArray(rawVal)) {
235
+ const allowedObjKeys = new Set(["enabled", "severity", "level", "priority"]);
236
+ for (const k of Object.keys(rawVal)) {
237
+ if (!allowedObjKeys.has(k)) {
238
+ throw new DislopConfigError(`Invalid key '${k}' in rule setting for '${ruleId}' in '${source}'`);
239
+ }
240
+ }
241
+ if (rawVal.enabled !== undefined && typeof rawVal.enabled !== "boolean") {
242
+ throw new DislopConfigError(`'enabled' for rule '${ruleId}' in '${source}' must be boolean`);
243
+ }
244
+ for (const sevKey of ["severity", "level", "priority"]) {
245
+ if (rawVal[sevKey] !== undefined) {
246
+ const s = String(rawVal[sevKey]).trim().toLowerCase();
247
+ if (!VALID_RULE_SEVERITIES.has(s)) {
248
+ throw new DislopConfigError(
249
+ `Invalid ${sevKey} '${rawVal[sevKey]}' for rule '${ruleId}' in '${source}'`,
250
+ );
251
+ }
252
+ }
253
+ }
254
+ return rawVal;
255
+ }
256
+ throw new DislopConfigError(`Invalid rule setting for '${ruleId}' in '${source}'`);
257
+ }
258
+
259
+ function validateDeclarativeRuleEntry(entry, index, source) {
260
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
261
+ throw new DislopConfigError(`Declarative rule #${index} in '${source}' must be an object`);
262
+ }
263
+ const id = String(entry.id || entry.ruleId || "").trim();
264
+ if (!id || !/^[a-z0-9][a-z0-9/_-]{1,80}$/i.test(id)) {
265
+ throw new DislopConfigError(
266
+ `Declarative rule #${index} in '${source}' requires a safe alphanumeric 'id'`,
267
+ );
268
+ }
269
+ const pattern = entry.pattern ? String(entry.pattern) : null;
270
+ const terms = Array.isArray(entry.terms)
271
+ ? entry.terms.map(String).filter(Boolean)
272
+ : typeof entry.literal === "string" && entry.literal
273
+ ? [entry.literal]
274
+ : [];
275
+ if (!pattern && terms.length === 0) {
276
+ throw new DislopConfigError(
277
+ `Declarative rule '${id}' in '${source}' must define 'pattern', 'literal', or 'terms'`,
278
+ );
279
+ }
280
+ if (pattern) {
281
+ if (pattern.length > 500) {
282
+ throw new DislopConfigError(`Declarative rule '${id}' pattern exceeds 500 chars`);
283
+ }
284
+ if (/(\+|\*|\{[^}]+\})\s*\)?\s*(\+|\*|\{[^}]+\})/.test(pattern)) {
285
+ throw new DislopConfigError(
286
+ `Declarative rule '${id}' contains nested quantifiers prohibited for ReDoS safety`,
287
+ );
288
+ }
289
+ try {
290
+ new RegExp(pattern, entry.flags ? String(entry.flags).replace(/[^imu]/g, "") : "i");
291
+ } catch (err) {
292
+ throw new DislopConfigError(`Declarative rule '${id}' has invalid RegExp: ${err.message}`);
293
+ }
294
+ }
295
+ const kind = entry.kind === "suggestion" ? "suggestion" : "defect";
296
+ const severity = entry.severity ? String(entry.severity).toLowerCase() : "warning";
297
+ if (!["error", "warning"].includes(severity)) {
298
+ throw new DislopConfigError(
299
+ `Declarative rule '${id}' has invalid severity '${entry.severity}'`,
300
+ );
301
+ }
302
+ const priority = entry.priority ? String(entry.priority).toLowerCase() : "moderate";
303
+ if (!["strong", "moderate", "hint"].includes(priority)) {
304
+ throw new DislopConfigError(
305
+ `Declarative rule '${id}' has invalid priority '${entry.priority}'`,
306
+ );
307
+ }
308
+ const fixSafety = entry.fixSafety ? String(entry.fixSafety).toLowerCase() : "review";
309
+ if (!["safe", "review", "manual"].includes(fixSafety)) {
310
+ throw new DislopConfigError(
311
+ `Declarative rule '${id}' has invalid fixSafety '${entry.fixSafety}'`,
312
+ );
313
+ }
314
+
315
+ return {
316
+ id,
317
+ kind,
318
+ severity,
319
+ priority,
320
+ fixSafety,
321
+ pattern,
322
+ flags: entry.flags ? String(entry.flags).replace(/[^imu]/g, "") : "i",
323
+ terms,
324
+ formats: Array.isArray(entry.formats) ? entry.formats.map(String) : null,
325
+ files: Array.isArray(entry.files)
326
+ ? entry.files.map(String)
327
+ : typeof entry.files === "string"
328
+ ? [entry.files]
329
+ : null,
330
+ languages: Array.isArray(entry.languages) ? entry.languages.map(String) : null,
331
+ reason: String(entry.reason || entry.message || `Matched project rule '${id}'.`),
332
+ replacement:
333
+ entry.replacement !== undefined
334
+ ? String(entry.replacement)
335
+ : entry.suggestedReplacement !== undefined
336
+ ? String(entry.suggestedReplacement)
337
+ : undefined,
338
+ actionType: entry.actionType ? String(entry.actionType) : undefined,
339
+ };
340
+ }
341
+
342
+ function loadProjectDeclarativeRulesFile(projectDir) {
343
+ const rulesPath = path.join(projectDir, ".dislop", "rules.json");
344
+ if (!fs.existsSync(rulesPath)) return [];
345
+ let raw;
346
+ try {
347
+ raw = JSON.parse(fs.readFileSync(rulesPath, "utf8"));
348
+ } catch (err) {
349
+ throw new DislopConfigError(`Invalid JSON in '${rulesPath}': ${err.message}`);
350
+ }
351
+ const entries = Array.isArray(raw) ? raw : Array.isArray(raw?.rules) ? raw.rules : null;
352
+ if (!entries) {
353
+ throw new DislopConfigError(`'${rulesPath}' must export an array or { rules: [...] }`);
354
+ }
355
+ return entries.map((e, idx) => validateDeclarativeRuleEntry(e, idx, rulesPath));
356
+ }
357
+
358
+ export function isCiEnvironment(env = process.env) {
359
+ return Boolean((env.CI && env.CI !== "0" && env.CI !== "false") || env.GITHUB_ACTIONS);
360
+ }
361
+
362
+ function parseConcurrencyValue(raw, label) {
363
+ const num = Number(raw);
364
+ if (!Number.isInteger(num) || num < 1 || num > 16) {
365
+ throw new DislopConfigError(`Invalid ${label} '${raw}' (expected integer 1..16)`);
366
+ }
367
+ return num;
368
+ }
369
+
370
+ function parseRetentionDaysValue(raw, label) {
371
+ const num = Number(raw);
372
+ if (!Number.isInteger(num) || num < 1 || num > 365) {
373
+ throw new DislopConfigError(`Invalid ${label} '${raw}' (expected integer 1..365)`);
374
+ }
375
+ return num;
376
+ }
377
+
378
+ /**
379
+ * Resolve layered configuration:
380
+ * `~/.config/dislop/config.json` <- `<projectDir>/.dislop.json` <- `<localDir>/.dislop.local.json` <- CLI flags.
381
+ */
382
+ export function resolveLayeredConfig({ cwd = process.cwd(), env = process.env, cliFlags = {} } = {}) {
383
+ const homeDir = getDislopHomeDir(env);
384
+ const userConfigPath = path.join(homeDir, "config.json");
385
+ const { projectDir, gitBoundary, projectConfigPath, localConfigPath } =
386
+ findProjectRootAndConfigs(cwd);
387
+ const localTrusted = isLocalConfigTrustedUntracked(localConfigPath, gitBoundary);
388
+
389
+ const defaults = {
390
+ routing: "local",
391
+ activeProvider: null,
392
+ approvedHosts: [],
393
+ ignore: [],
394
+ concurrency: null,
395
+ packs: null,
396
+ extraPacks: [],
397
+ extraPackSpecs: [],
398
+ packOrigin: "default",
399
+ projectDir,
400
+ overrides: [],
401
+ rules: {},
402
+ declarativeRules: [],
403
+ failOn: "error",
404
+ lang: "auto",
405
+ level: "all",
406
+ voice: {
407
+ referenceFiles: [],
408
+ cachePath: path.join(homeDir, "voice.json"),
409
+ },
410
+ worklog: {
411
+ enabled: false,
412
+ privacy: "metadata",
413
+ dir: path.join(homeDir, "worklog"),
414
+ retentionDays: 30,
415
+ },
416
+ providers: {},
417
+ };
418
+
419
+ const layers = [
420
+ { source: userConfigPath, origin: "user", data: readJsonFileStrict(userConfigPath), isLocalTrusted: true },
421
+ { source: projectConfigPath, origin: "project", data: readJsonFileStrict(projectConfigPath), isLocalTrusted: false },
422
+ { source: localConfigPath, origin: localTrusted ? "local" : "project", data: readJsonFileStrict(localConfigPath), isLocalTrusted: localTrusted },
423
+ ];
424
+
425
+ const merged = structuredClone(defaults);
426
+ const loadedSources = [];
427
+
428
+ for (const layer of layers) {
429
+ if (!layer.data) continue;
430
+ loadedSources.push(layer.source);
431
+ const d = layer.data;
432
+
433
+ if (!layer.isLocalTrusted) {
434
+ validateProjectLayerKeys(d, layer.source);
435
+ }
436
+
437
+ if (d.routing !== undefined) {
438
+ if (!VALID_ROUTING_MODES.has(d.routing)) {
439
+ throw new DislopConfigError(
440
+ `Invalid 'routing' value '${d.routing}' in '${layer.source}' (expected off, local, auto, cloud, or byok)`,
441
+ );
442
+ }
443
+ if (!layer.isLocalTrusted && !VALID_PROJECT_ROUTING_MODES.has(d.routing)) {
444
+ throw new DislopConfigError(
445
+ `Shared project '${layer.source}' cannot set routing '${d.routing}' (only 'local' or 'off' allowed; set 'byok'/'cloud'/'auto' in user or local config).`,
446
+ );
447
+ }
448
+ merged.routing = d.routing;
449
+ }
450
+ if (layer.isLocalTrusted && d.activeProvider !== undefined) {
451
+ merged.activeProvider = d.activeProvider ? String(d.activeProvider) : null;
452
+ }
453
+ if (layer.isLocalTrusted && d.approvedHosts !== undefined) {
454
+ if (!Array.isArray(d.approvedHosts)) {
455
+ throw new DislopConfigError(`'approvedHosts' in '${layer.source}' must be an array`);
456
+ }
457
+ merged.approvedHosts = Array.from(new Set([...merged.approvedHosts, ...d.approvedHosts.map(String)]));
458
+ }
459
+ if (d.ignore !== undefined) {
460
+ if (!Array.isArray(d.ignore)) {
461
+ throw new DislopConfigError(`'ignore' in '${layer.source}' must be an array`);
462
+ }
463
+ merged.ignore = Array.from(new Set([...merged.ignore, ...d.ignore.map((v) => String(v).trim()).filter(Boolean)]));
464
+ }
465
+ if (d.concurrency !== undefined && d.concurrency !== null) {
466
+ merged.concurrency = parseConcurrencyValue(d.concurrency, `'concurrency' in '${layer.source}'`);
467
+ }
468
+ if (d.packs !== undefined) {
469
+ if (!Array.isArray(d.packs)) {
470
+ throw new DislopConfigError(`'packs' in '${layer.source}' must be an array`);
471
+ }
472
+ merged.packs = d.packs.map(String);
473
+ merged.packOrigin = layer.origin;
474
+ }
475
+ if (d.extraPacks !== undefined) {
476
+ if (!Array.isArray(d.extraPacks)) {
477
+ throw new DislopConfigError(`'extraPacks' in '${layer.source}' must be an array`);
478
+ }
479
+ for (const ep of d.extraPacks) {
480
+ if (typeof ep !== "string" || !ep.trim()) {
481
+ throw new DislopConfigError(`Each entry in 'extraPacks' in '${layer.source}' must be a non-empty string`);
482
+ }
483
+ const s = ep.trim();
484
+ if (!merged.extraPacks.includes(s)) {
485
+ merged.extraPacks.push(s);
486
+ merged.extraPackSpecs.push({ spec: s, origin: layer.origin });
487
+ } else {
488
+ // If added earlier and also listed from a stricter untrusted origin, keep untrusted origin
489
+ const existing = merged.extraPackSpecs.find((x) => x.spec === s);
490
+ if (existing && !layer.isLocalTrusted) {
491
+ existing.origin = layer.origin;
492
+ }
493
+ }
494
+ }
495
+ }
496
+ if (d.failOn !== undefined) {
497
+ merged.failOn = normalizeFailOnValue(d.failOn, `'failOn' in '${layer.source}'`);
498
+ }
499
+ if (d.lang !== undefined) {
500
+ merged.lang = String(d.lang);
501
+ }
502
+ if (d.level !== undefined) {
503
+ merged.level = String(d.level);
504
+ }
505
+ if (d.rules !== undefined) {
506
+ if (Array.isArray(d.rules)) {
507
+ merged.declarativeRules.push(
508
+ ...d.rules.map((e, idx) => validateDeclarativeRuleEntry(e, idx, layer.source)),
509
+ );
510
+ } else if (d.rules && typeof d.rules === "object") {
511
+ for (const [rId, rVal] of Object.entries(d.rules)) {
512
+ merged.rules[rId] = validateRuleConfigValue(rId, rVal, layer.source);
513
+ }
514
+ } else {
515
+ throw new DislopConfigError(`'rules' in '${layer.source}' must be an object or array`);
516
+ }
517
+ }
518
+ if (d.overrides !== undefined) {
519
+ if (!Array.isArray(d.overrides)) {
520
+ throw new DislopConfigError(`'overrides' in '${layer.source}' must be an array`);
521
+ }
522
+ for (let i = 0; i < d.overrides.length; i++) {
523
+ const ov = d.overrides[i];
524
+ if (!ov || typeof ov !== "object" || Array.isArray(ov)) {
525
+ throw new DislopConfigError(`overrides[${i}] in '${layer.source}' must be an object`);
526
+ }
527
+ if (!ov.files || (typeof ov.files !== "string" && !Array.isArray(ov.files))) {
528
+ throw new DislopConfigError(
529
+ `overrides[${i}] in '${layer.source}' must define 'files' (string or array)`,
530
+ );
531
+ }
532
+ const ovAllowed = new Set(["files", "packs", "extraPacks", "rules", "failOn", "lang", "level", "ignore", "routing"]);
533
+ for (const k of Object.keys(ov)) {
534
+ if (!ovAllowed.has(k)) {
535
+ throw new DislopConfigError(`Invalid override key '${k}' in '${layer.source}'`);
536
+ }
537
+ }
538
+ if (ov.routing !== undefined && !layer.isLocalTrusted && !VALID_PROJECT_ROUTING_MODES.has(ov.routing)) {
539
+ throw new DislopConfigError(
540
+ `overrides[${i}].routing in '${layer.source}' only permits 'local' or 'off'`,
541
+ );
542
+ }
543
+ const filesList = Array.isArray(ov.files) ? ov.files : [ov.files];
544
+ if (filesList.length === 0 || filesList.some((f) => typeof f !== "string" || !f.trim())) {
545
+ throw new DislopConfigError(
546
+ `overrides[${i}].files in '${layer.source}' must contain only non-empty strings`,
547
+ );
548
+ }
549
+ for (const arrField of ["packs", "extraPacks", "ignore"]) {
550
+ if (
551
+ ov[arrField] !== undefined &&
552
+ (!Array.isArray(ov[arrField]) || ov[arrField].some((x) => typeof x !== "string"))
553
+ ) {
554
+ throw new DislopConfigError(
555
+ `overrides[${i}].${arrField} in '${layer.source}' must be an array of strings`,
556
+ );
557
+ }
558
+ }
559
+ merged.overrides.push({
560
+ files: filesList.map((f) => f.trim()),
561
+ packs: Array.isArray(ov.packs) ? ov.packs : undefined,
562
+ extraPacks: Array.isArray(ov.extraPacks) ? ov.extraPacks : undefined,
563
+ failOn: ov.failOn !== undefined ? normalizeFailOnValue(ov.failOn, `overrides[${i}].failOn`) : undefined,
564
+ lang: ov.lang !== undefined ? String(ov.lang) : undefined,
565
+ level: ov.level !== undefined ? String(ov.level) : undefined,
566
+ ignore: Array.isArray(ov.ignore) ? ov.ignore : undefined,
567
+ routing: ov.routing !== undefined ? String(ov.routing) : undefined,
568
+ origin: layer.origin,
569
+ rules:
570
+ ov.rules && typeof ov.rules === "object" && !Array.isArray(ov.rules)
571
+ ? Object.fromEntries(
572
+ Object.entries(ov.rules).map(([rk, rv]) => [
573
+ rk,
574
+ validateRuleConfigValue(rk, rv, layer.source),
575
+ ]),
576
+ )
577
+ : undefined,
578
+ });
579
+ }
580
+ }
581
+ if (d.voice !== undefined) {
582
+ if (!d.voice || typeof d.voice !== "object" || Array.isArray(d.voice)) {
583
+ throw new DislopConfigError(`'voice' in '${layer.source}' must be an object`);
584
+ }
585
+ if (!layer.isLocalTrusted) {
586
+ for (const vk of Object.keys(d.voice)) {
587
+ if (vk !== "referenceFiles") {
588
+ throw new DislopConfigError(
589
+ `'voice.${vk}' is not permitted in shared project '${layer.source}'`,
590
+ );
591
+ }
592
+ }
593
+ }
594
+ if (Array.isArray(d.voice.referenceFiles)) {
595
+ const baseDir = path.dirname(layer.source);
596
+ merged.voice.referenceFiles = d.voice.referenceFiles.map((f) => {
597
+ const resolved = path.resolve(baseDir, expandTilde(f, env));
598
+ if (!layer.isLocalTrusted && !isPathInsideDir(resolved, projectDir)) {
599
+ throw new DislopConfigError(
600
+ `'voice.referenceFiles' entry '${f}' in '${layer.source}' escapes project directory '${projectDir}'`,
601
+ );
602
+ }
603
+ return resolved;
604
+ });
605
+ }
606
+ if (layer.isLocalTrusted && d.voice.cachePath) {
607
+ const resolvedCache = path.resolve(cwd, expandTilde(d.voice.cachePath, env));
608
+ if (layer.origin !== "user" && !isPathInsideDir(resolvedCache, homeDir) && !isPathInsideDir(resolvedCache, projectDir)) {
609
+ throw new DislopConfigError(
610
+ `'voice.cachePath' '${d.voice.cachePath}' must stay inside dislop config dir or project root`,
611
+ );
612
+ }
613
+ merged.voice.cachePath = resolvedCache;
614
+ }
615
+ }
616
+ if (layer.isLocalTrusted && d.providers && typeof d.providers === "object" && !Array.isArray(d.providers)) {
617
+ for (const [provName, provCfg] of Object.entries(d.providers)) {
618
+ if (!provCfg || typeof provCfg !== "object") continue;
619
+ merged.providers[provName] = { ...merged.providers[provName], ...provCfg };
620
+ }
621
+ }
622
+ if (layer.isLocalTrusted && d.worklog !== undefined) {
623
+ if (!d.worklog || typeof d.worklog !== "object" || Array.isArray(d.worklog)) {
624
+ throw new DislopConfigError(`'worklog' in '${layer.source}' must be an object`);
625
+ }
626
+ if (d.worklog.enabled !== undefined) {
627
+ if (typeof d.worklog.enabled !== "boolean") {
628
+ throw new DislopConfigError(`'worklog.enabled' in '${layer.source}' must be a boolean`);
629
+ }
630
+ merged.worklog.enabled = d.worklog.enabled;
631
+ }
632
+ if (d.worklog.privacy !== undefined) {
633
+ const priv = String(d.worklog.privacy).trim();
634
+ if (!VALID_WORKLOG_PRIVACY_MODES.has(priv)) {
635
+ throw new DislopConfigError(
636
+ `Invalid 'worklog.privacy' value '${d.worklog.privacy}' in '${layer.source}' (expected metadata, redacted, or local-full)`,
637
+ );
638
+ }
639
+ merged.worklog.privacy = priv;
640
+ }
641
+ if (d.worklog.dir !== undefined && d.worklog.dir !== null) {
642
+ if (typeof d.worklog.dir !== "string" || !d.worklog.dir.trim()) {
643
+ throw new DislopConfigError(`'worklog.dir' in '${layer.source}' must be a non-empty string`);
644
+ }
645
+ merged.worklog.dir = path.resolve(
646
+ path.dirname(layer.source),
647
+ expandTilde(d.worklog.dir.trim(), env),
648
+ );
649
+ }
650
+ if (d.worklog.retentionDays !== undefined && d.worklog.retentionDays !== null) {
651
+ merged.worklog.retentionDays = parseRetentionDaysValue(
652
+ d.worklog.retentionDays,
653
+ `'worklog.retentionDays' in '${layer.source}'`,
654
+ );
655
+ }
656
+ }
657
+ }
658
+
659
+ // Apply environment variable overrides for local worklog recording
660
+ if (env.DISLOP_WORKLOG !== undefined && String(env.DISLOP_WORKLOG).trim() !== "") {
661
+ const rawWl = String(env.DISLOP_WORKLOG).trim().toLowerCase();
662
+ if (rawWl === "0" || rawWl === "false" || rawWl === "off") {
663
+ merged.worklog.enabled = false;
664
+ } else if (rawWl === "1" || rawWl === "true" || rawWl === "on") {
665
+ merged.worklog.enabled = true;
666
+ } else if (VALID_WORKLOG_PRIVACY_MODES.has(rawWl)) {
667
+ merged.worklog.enabled = true;
668
+ merged.worklog.privacy = rawWl;
669
+ } else {
670
+ throw new DislopConfigError(
671
+ `Invalid DISLOP_WORKLOG '${env.DISLOP_WORKLOG}' (expected 0/1/false/true/off/on/metadata/redacted/local-full)`,
672
+ );
673
+ }
674
+ }
675
+ if (env.DISLOP_WORKLOG_DIR !== undefined && String(env.DISLOP_WORKLOG_DIR).trim() !== "") {
676
+ merged.worklog.dir = path.resolve(cwd, expandTilde(String(env.DISLOP_WORKLOG_DIR).trim(), env));
677
+ }
678
+ if (
679
+ env.DISLOP_WORKLOG_RETENTION_DAYS !== undefined &&
680
+ String(env.DISLOP_WORKLOG_RETENTION_DAYS).trim() !== ""
681
+ ) {
682
+ merged.worklog.retentionDays = parseRetentionDaysValue(
683
+ env.DISLOP_WORKLOG_RETENTION_DAYS,
684
+ "DISLOP_WORKLOG_RETENTION_DAYS",
685
+ );
686
+ }
687
+
688
+ const projectDeclarativeRules = loadProjectDeclarativeRulesFile(projectDir);
689
+ if (projectDeclarativeRules.length > 0) {
690
+ merged.declarativeRules.push(...projectDeclarativeRules);
691
+ }
692
+
693
+ // Apply CLI flag overrides
694
+ const explicitEngine = Boolean(cliFlags.engine);
695
+ if (cliFlags.engine) {
696
+ if (!VALID_ROUTING_MODES.has(cliFlags.engine)) {
697
+ throw new DislopConfigError(
698
+ `Invalid --engine '${cliFlags.engine}' (expected off, auto, cloud, byok, or local)`,
699
+ );
700
+ }
701
+ merged.routing = cliFlags.engine;
702
+ }
703
+ if (cliFlags.provider) {
704
+ merged.activeProvider = String(cliFlags.provider);
705
+ }
706
+ if (cliFlags.packs && cliFlags.packs.length > 0) {
707
+ merged.packs = cliFlags.packs;
708
+ merged.packOrigin = cliFlags.packOrigin || "cli";
709
+ }
710
+ if (cliFlags.failOn) {
711
+ merged.failOn = normalizeFailOnValue(cliFlags.failOn, "--fail-on");
712
+ }
713
+ if (cliFlags.lang) {
714
+ if (!["auto", "en", "zh"].includes(cliFlags.lang)) {
715
+ throw new DislopConfigError(`Invalid --lang '${cliFlags.lang}' (expected auto, en, or zh)`);
716
+ }
717
+ merged.lang = cliFlags.lang;
718
+ }
719
+ if (cliFlags.level) {
720
+ if (!["strong", "moderate", "hint", "all"].includes(cliFlags.level)) {
721
+ throw new DislopConfigError(
722
+ `Invalid --level '${cliFlags.level}' (expected strong, moderate, hint, or all)`,
723
+ );
724
+ }
725
+ merged.level = cliFlags.level;
726
+ }
727
+ if (cliFlags.voiceFiles && cliFlags.voiceFiles.length > 0) {
728
+ merged.voice.referenceFiles = cliFlags.voiceFiles.map((f) => path.resolve(cwd, expandTilde(f, env)));
729
+ }
730
+ if (cliFlags.concurrency !== undefined && cliFlags.concurrency !== null && cliFlags.concurrency !== "") {
731
+ merged.concurrency = parseConcurrencyValue(cliFlags.concurrency, "--concurrency");
732
+ }
733
+
734
+ return {
735
+ ...merged,
736
+ explicitEngine,
737
+ explicitFailOn: Boolean(cliFlags.failOn),
738
+ modelOverride: cliFlags.model ? String(cliFlags.model) : null,
739
+ noLlm: Boolean(cliFlags.noLlm) || env.DISLOP_TEST_MODE === "1" || merged.routing === "off",
740
+ homeDir,
741
+ userConfigPath,
742
+ credentialsPath: path.join(homeDir, "credentials.json"),
743
+ modelsDir: path.join(homeDir, "models"),
744
+ loadedSources,
745
+ };
746
+ }
747
+
748
+ export function computeFilesFingerprint(filePaths) {
749
+ const hash = crypto.createHash("sha256");
750
+ const sorted = [...filePaths].sort();
751
+ for (const fp of sorted) {
752
+ if (!fs.existsSync(fp)) continue;
753
+ hash.update(fp);
754
+ hash.update("\0");
755
+ hash.update(fs.readFileSync(fp));
756
+ hash.update("\0");
757
+ }
758
+ return hash.digest("hex");
759
+ }