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,84 @@
1
+ import fs from "node:fs";
2
+ import {
3
+ DislopConfigError,
4
+ isInteractiveHumanTty,
5
+ readJsonFileStrict,
6
+ resolveLayeredConfig,
7
+ writeJsonFileSecure,
8
+ } from "../kernel/config.mjs";
9
+ import { expandTargetInputs } from "../kernel/file-discovery.mjs";
10
+ import { extractVoiceProfile } from "../kernel/voice-profile.mjs";
11
+ import { resolveExecutionRoute } from "../runtime/router.mjs";
12
+
13
+ /**
14
+ * `dislop voice <extract|show|clear> [files/globs...]`
15
+ */
16
+ export async function runVoiceCommand(positionals, flags, io = {}) {
17
+ const {
18
+ cwd = process.cwd(),
19
+ env = process.env,
20
+ stdin = process.stdin,
21
+ stdout = process.stdout,
22
+ stderr = process.stderr,
23
+ fetchImpl = globalThis.fetch,
24
+ } = io;
25
+
26
+ const action = positionals[0] || "show";
27
+ const targets = positionals.slice(1);
28
+ const config = resolveLayeredConfig({ cwd, env, cliFlags: flags });
29
+ const cachePath = config.voice.cachePath;
30
+
31
+ if (action === "show") {
32
+ if (!fs.existsSync(cachePath)) {
33
+ stdout.write(`No cached voice profile at ${cachePath}. Run 'dislop voice extract <files...>'.\n`);
34
+ return 0;
35
+ }
36
+ const profile = readJsonFileStrict(cachePath);
37
+ if (flags.json || flags.format === "json") {
38
+ stdout.write(`${JSON.stringify(profile, null, 2)}\n`);
39
+ } else {
40
+ stdout.write(`Voice Profile (${cachePath}):\n`);
41
+ stdout.write(` Language : ${profile.language}\n`);
42
+ stdout.write(` Summary : ${profile.summary}\n`);
43
+ stdout.write(` Anchors : ${(profile.voiceAnchors || []).join("; ") || "(none)"}\n`);
44
+ stdout.write(` Connectors : ${(profile.preferredConnectors || []).join(", ") || "(none)"}\n`);
45
+ }
46
+ return 0;
47
+ }
48
+
49
+ if (action === "clear") {
50
+ if (fs.existsSync(cachePath)) {
51
+ fs.unlinkSync(cachePath);
52
+ stdout.write(`Cleared voice profile at ${cachePath}\n`);
53
+ } else {
54
+ stdout.write("No cached voice profile to clear.\n");
55
+ }
56
+ return 0;
57
+ }
58
+
59
+ if (action === "extract") {
60
+ const fileInputs = targets.length > 0 ? targets : config.voice.referenceFiles;
61
+ if (!fileInputs || fileInputs.length === 0) {
62
+ throw new DislopConfigError(
63
+ "Usage: dislop voice extract <files/globs...> (no reference files provided)",
64
+ );
65
+ }
66
+ const resolvedFiles = expandTargetInputs(fileInputs, { cwd, ignorePatterns: config.ignore });
67
+ const isTty = isInteractiveHumanTty({ stdin, stdout, env });
68
+ const route = await resolveExecutionRoute({ config, isTty, env, stdin, stderr, fetchImpl });
69
+ const profile = await extractVoiceProfile(resolvedFiles, { route });
70
+ writeJsonFileSecure(cachePath, profile, { mode: 0o600 });
71
+
72
+ if (flags.json || flags.format === "json") {
73
+ stdout.write(`${JSON.stringify(profile, null, 2)}\n`);
74
+ } else {
75
+ stdout.write(`Saved personal voice profile to ${cachePath} (${resolvedFiles.length} file(s)).\n`);
76
+ stdout.write(` Summary: ${profile.summary}\n`);
77
+ }
78
+ return 0;
79
+ }
80
+
81
+ throw new DislopConfigError(
82
+ `Unknown 'dislop voice' subcommand '${action}' (expected extract, show, or clear)`,
83
+ );
84
+ }
@@ -0,0 +1,424 @@
1
+ import { DislopConfigError, isCiEnvironment, resolveLayeredConfig } from "../kernel/config.mjs";
2
+ import {
3
+ buildReflectionReport,
4
+ clearWorklogEntries,
5
+ computeWorklogStats,
6
+ findWorklogEntryById,
7
+ getWorklogStorageStats,
8
+ isWorklogActive,
9
+ readWorklogEntries,
10
+ } from "../runtime/worklog.mjs";
11
+
12
+ function parseBoundedInt(raw, label, min, max) {
13
+ const num = Number(raw);
14
+ if (!Number.isInteger(num) || num < min || num > max) {
15
+ throw new DislopConfigError(`Invalid ${label} '${raw}' (expected integer ${min}..${max})`);
16
+ }
17
+ return num;
18
+ }
19
+
20
+ function formatBytes(bytes) {
21
+ if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes || 0} B`;
22
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
23
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
24
+ }
25
+
26
+ function renderStatusText(status) {
27
+ const stateLabel = status.active
28
+ ? "active"
29
+ : status.ciDisabled
30
+ ? "disabled (suppressed in CI environment)"
31
+ : "disabled (off by default)";
32
+
33
+ const lines = [
34
+ "dislop worklog",
35
+ ` State : ${stateLabel}`,
36
+ ` Privacy Tier : ${status.privacy}`,
37
+ ` Storage Dir : ${status.dir}`,
38
+ ` Retention Days : ${status.retentionDays}`,
39
+ ` Stored Files : ${status.fileCount} daily file(s), ${status.entryCount} entry(ies), ${formatBytes(status.totalBytes)}`,
40
+ ];
41
+
42
+ if (!status.enabled) {
43
+ lines.push(
44
+ " Enable Locally : set DISLOP_WORKLOG=1 or add {\"worklog\":{\"enabled\":true}} in .dislop.local.json or ~/.config/dislop/config.json",
45
+ );
46
+ }
47
+ return `${lines.join("\n")}\n`;
48
+ }
49
+
50
+ function renderListText(entries, windowDays) {
51
+ if (entries.length === 0) {
52
+ return `No worklog entries found in the last ${windowDays} day(s).\n`;
53
+ }
54
+
55
+ const lines = [`Recent worklog entries (${entries.length}, window=${windowDays}d):`];
56
+ for (const e of entries) {
57
+ const shortId = String(e.id || "").slice(0, 8);
58
+ const ts = String(e.timestamp || "").replace("T", " ").slice(0, 19);
59
+ const cmdLabel = e.mode ? `${e.source || "cli"}:${e.command}/${e.mode}` : `${e.source || "cli"}:${e.command}`;
60
+ if (e.verify) {
61
+ lines.push(
62
+ ` ${shortId} ${ts} ${cmdLabel} verify=${e.verify.ok ? "PASS" : "FAIL"} dropped=${e.verify.droppedFactsCount || 0} regressions=${(e.verify.regressionIds || []).length} ${e.durationMs || 0}ms exit=${e.exitCode ?? 0}`,
63
+ );
64
+ } else {
65
+ const s = e.summary || {};
66
+ const defects = (s.defects?.error || 0) + (s.defects?.warning || 0);
67
+ const suggestions =
68
+ (s.suggestions?.strong || 0) + (s.suggestions?.moderate || 0) + (s.suggestions?.hint || 0);
69
+ lines.push(
70
+ ` ${shortId} ${ts} ${cmdLabel} engine=${e.engine || "deterministic"} files=${e.fileCount || 0} defects=${defects} suggestions=${suggestions} applied=${s.applied || 0} skipped=${s.skipped || 0} ${e.durationMs || 0}ms exit=${e.exitCode ?? 0}`,
71
+ );
72
+ }
73
+ }
74
+ return `${lines.join("\n")}\n`;
75
+ }
76
+
77
+ function renderEntryDetailText(entry) {
78
+ const lines = [
79
+ `Worklog Entry ${entry.id}`,
80
+ ` Timestamp : ${entry.timestamp}`,
81
+ ` Source/Command : ${entry.source || "cli"}:${entry.command}${entry.mode ? ` (${entry.mode})` : ""}`,
82
+ ` Version : ${entry.version || "unknown"}`,
83
+ ` Privacy Tier : ${entry.privacy}`,
84
+ ` Workspace : ${entry.workspaceName ? `${entry.workspaceName} (${entry.workspaceHash})` : entry.workspaceHash}`,
85
+ ` Engine/Routing : ${entry.engine} (routing=${entry.routing}${entry.routeFallback ? ", fallback=yes" : ""})`,
86
+ ` Duration/Exit : ${entry.durationMs}ms (exit=${entry.exitCode})`,
87
+ ];
88
+
89
+ if (entry.verify) {
90
+ lines.push(
91
+ ` Verify : ${entry.verify.ok ? "PASS" : "FAIL"} (droppedFacts=${entry.verify.droppedFactsCount || 0}, regressions=${(entry.verify.regressionIds || []).join(", ") || "none"})`,
92
+ );
93
+ if ((entry.verify.droppedFactTypes || []).length > 0) {
94
+ lines.push(` Dropped Types : ${entry.verify.droppedFactTypes.join(", ")}`);
95
+ }
96
+ if (Array.isArray(entry.verify.droppedFacts) && entry.verify.droppedFacts.length > 0) {
97
+ lines.push(` Dropped Detail : ${entry.verify.droppedFacts.join(" | ")}`);
98
+ }
99
+ } else {
100
+ const s = entry.summary || {};
101
+ lines.push(
102
+ ` Summary : defects(err=${s.defects?.error || 0}, warn=${s.defects?.warning || 0}) suggestions(strong=${s.suggestions?.strong || 0}, mod=${s.suggestions?.moderate || 0}, hint=${s.suggestions?.hint || 0}) applied=${s.applied || 0} edited=${s.edited || 0} skipped=${s.skipped || 0} factGateDowngraded=${s.factGateDowngraded || 0}`,
103
+ );
104
+ for (const fileRec of entry.files || []) {
105
+ const label = fileRec.fileRef || `${fileRec.fileHash}.${fileRec.ext}`;
106
+ lines.push(
107
+ ` File : ${label} (${fileRec.language}/${fileRec.modality}, segments=${fileRec.segmentCount}, ${fileRec.durationMs ?? "-"}ms, findings=${(fileRec.findings || []).length})`,
108
+ );
109
+ for (const f of fileRec.findings || []) {
110
+ const extra = [
111
+ f.origin,
112
+ f.fixSafety,
113
+ f.decision ? `decision=${f.decision}` : null,
114
+ f.factGateDowngraded ? `factGate=[${(f.factGateCategories || []).join(",")}]` : null,
115
+ ]
116
+ .filter(Boolean)
117
+ .join(", ");
118
+ lines.push(` - [${f.kind}:${f.severityOrPriority}] ${f.ruleId} (${extra})`);
119
+ if (f.quotePreview || f.originalQuote) {
120
+ lines.push(` quote: ${f.quotePreview || f.originalQuote}`);
121
+ }
122
+ }
123
+ }
124
+ }
125
+
126
+ return `${lines.join("\n")}\n`;
127
+ }
128
+
129
+ function renderStatsText(stats, windowDays) {
130
+ const lines = [
131
+ `dislop worklog stats (window=${windowDays}d)`,
132
+ ` Total Runs : ${stats.totalRuns} (${stats.totalFiles} file inspections)`,
133
+ ` By Command : ${Object.entries(stats.byCommand).map(([k, v]) => `${k}=${v}`).join(", ") || "none"}`,
134
+ ` By Source : ${Object.entries(stats.bySource).map(([k, v]) => `${k}=${v}`).join(", ") || "none"}`,
135
+ ` By Engine : ${Object.entries(stats.byEngine).map(([k, v]) => `${k}=${v}`).join(", ") || "none"}`,
136
+ ` Route Fallback : ${stats.fallbackRuns} (${Math.round(stats.fallbackRate * 100)}%)`,
137
+ ` Latency : p50=${stats.latency.p50Ms}ms, p95=${stats.latency.p95Ms}ms, max=${stats.latency.maxMs}ms`,
138
+ ` Findings : defects(err=${stats.findingsSummary.defects.error}, warn=${stats.findingsSummary.defects.warning}) suggestions(strong=${stats.findingsSummary.suggestions.strong}, mod=${stats.findingsSummary.suggestions.moderate}, hint=${stats.findingsSummary.suggestions.hint})`,
139
+ ` Fix Decisions : applied=${stats.findingsSummary.applied}, edited=${stats.findingsSummary.edited}, skipped=${stats.findingsSummary.skipped}, promptCopied=${stats.findingsSummary.promptCopied}, factGateDowngraded=${stats.findingsSummary.factGateDowngraded}`,
140
+ ` Verify : total=${stats.verify.total}, passed=${stats.verify.passed}, failed=${stats.verify.failed}`,
141
+ ];
142
+
143
+ if (stats.rules.length > 0) {
144
+ lines.push(" Top Rules:");
145
+ for (const r of stats.rules.slice(0, 15)) {
146
+ const skipStr = r.skipRate !== null ? ` skipRate=${Math.round(r.skipRate * 100)}%` : "";
147
+ const fgStr = r.factGateDowngrades > 0 ? ` fgDowngrades=${r.factGateDowngrades}` : "";
148
+ lines.push(
149
+ ` - ${r.ruleId} [${r.kind}] hits=${r.hits} (det=${r.deterministicHits}, llm=${r.llmHits}) applied=${r.accepted + r.autoApplied} edited=${r.edited} skipped=${r.skipped}${skipStr}${fgStr}`,
150
+ );
151
+ }
152
+ }
153
+ return `${lines.join("\n")}\n`;
154
+ }
155
+
156
+ function renderReflectMarkdown(report) {
157
+ const { stats, signals, windowDays } = report;
158
+ const lines = [
159
+ `# dislop Worklog Reflection (${windowDays}d)`,
160
+ "",
161
+ `- Total runs: **${stats.totalRuns}** (${stats.totalFiles} file inspections)`,
162
+ `- Latency: p50 **${stats.latency.p50Ms}ms**, p95 **${stats.latency.p95Ms}ms**, max **${stats.latency.maxMs}ms**`,
163
+ `- Routing fallbacks: **${stats.fallbackRuns}** (${Math.round(stats.fallbackRate * 100)}%)`,
164
+ `- Fact Gate downgrades: **${stats.findingsSummary.factGateDowngraded}**`,
165
+ `- Verify checks: **${stats.verify.total}** (failed: **${stats.verify.failed}**)`,
166
+ "",
167
+ "## 1. High-Skip Rules (Possible False Positives / Noise)",
168
+ ];
169
+
170
+ if (signals.highSkipRules.length === 0) {
171
+ lines.push("- None observed (requires >=3 interactive fix decisions and >=50% skip rate).");
172
+ } else {
173
+ for (const r of signals.highSkipRules) {
174
+ lines.push(
175
+ `- \`${r.ruleId}\` (${r.pack}): skipped **${r.skipped}/${r.interactiveDecisions}** (${Math.round(r.skipRate * 100)}%) — ${r.recommendation}`,
176
+ );
177
+ }
178
+ }
179
+
180
+ lines.push("", "## 2. Frequently Edited Rules (Improve Suggested Fix / Prompt)");
181
+ if (signals.highEditRules.length === 0) {
182
+ lines.push("- None observed (requires >=2 manual `[e]` edits).");
183
+ } else {
184
+ for (const r of signals.highEditRules) {
185
+ lines.push(
186
+ `- \`${r.ruleId}\` (${r.pack}): manually edited **${r.edited}** time(s) across ${r.hits} hits — ${r.recommendation}`,
187
+ );
188
+ }
189
+ }
190
+
191
+ lines.push("", "## 3. Fact Gate Downgrade Hotspots");
192
+ if (signals.factGateHotspots.length === 0) {
193
+ lines.push("- None observed.");
194
+ } else {
195
+ for (const r of signals.factGateHotspots) {
196
+ const cats = Object.entries(r.categories)
197
+ .map(([k, v]) => `${k}:${v}`)
198
+ .join(", ");
199
+ lines.push(
200
+ `- \`${r.ruleId}\` (${r.pack}): **${r.downgrades}** downgrade(s) [${cats || "other"}] — ${r.recommendation}`,
201
+ );
202
+ }
203
+ }
204
+
205
+ lines.push("", "## 4. Verify Regressions & Dropped Fact Categories");
206
+ if (signals.verifyHotspots.total === 0) {
207
+ lines.push("- No `verify` runs recorded in window.");
208
+ } else {
209
+ lines.push(
210
+ `- Pass rate: **${signals.verifyHotspots.total - signals.verifyHotspots.failed}/${signals.verifyHotspots.total}** (failRate=${Math.round(signals.verifyHotspots.failRate * 100)}%)`,
211
+ );
212
+ if (signals.verifyHotspots.droppedFactTypes.length > 0) {
213
+ lines.push(
214
+ `- Dropped fact categories: ${signals.verifyHotspots.droppedFactTypes.map((d) => `\`${d.type}\` (${d.count})`).join(", ")}`,
215
+ );
216
+ }
217
+ if (signals.verifyHotspots.regressionIds.length > 0) {
218
+ lines.push(
219
+ `- Second-order regressions: ${signals.verifyHotspots.regressionIds.map((r) => `\`${r.id}\` (${r.count})`).join(", ")}`,
220
+ );
221
+ }
222
+ }
223
+
224
+ lines.push("", "## 5. Slow Files & Routing Friction");
225
+ if (signals.slowFiles.length === 0) {
226
+ lines.push("- No slow files exceeded latency thresholds (>500ms deterministic, >5000ms LLM).");
227
+ } else {
228
+ for (const sf of signals.slowFiles.slice(0, 10)) {
229
+ lines.push(
230
+ `- \`${sf.file}\` (${sf.ext}/${sf.modality}, ${sf.engine}): **${sf.durationMs}ms** across ${sf.segmentCount} segments`,
231
+ );
232
+ }
233
+ }
234
+ if (signals.routingFriction.recommendation) {
235
+ lines.push(`- Routing friction: ${signals.routingFriction.recommendation}`);
236
+ }
237
+
238
+ return `${lines.join("\n")}\n`;
239
+ }
240
+
241
+ function renderReflectText(report) {
242
+ const { stats, signals, windowDays } = report;
243
+ const lines = [
244
+ `dislop worklog reflect (window=${windowDays}d)`,
245
+ ` Runs=${stats.totalRuns}, Files=${stats.totalFiles}, p50=${stats.latency.p50Ms}ms, p95=${stats.latency.p95Ms}ms, Fallbacks=${stats.fallbackRuns}, FactGateDowngrades=${stats.findingsSummary.factGateDowngraded}, VerifyFailed=${stats.verify.failed}/${stats.verify.total}`,
246
+ "",
247
+ "Signals:",
248
+ ];
249
+
250
+ let anySignal = false;
251
+ for (const r of signals.highSkipRules) {
252
+ anySignal = true;
253
+ lines.push(` [HIGH-SKIP] ${r.ruleId}: ${r.skipped}/${r.interactiveDecisions} (${Math.round(r.skipRate * 100)}%)`);
254
+ }
255
+ for (const r of signals.highEditRules) {
256
+ anySignal = true;
257
+ lines.push(` [HIGH-EDIT] ${r.ruleId}: edited ${r.edited} time(s)`);
258
+ }
259
+ for (const r of signals.factGateHotspots) {
260
+ anySignal = true;
261
+ const cats = Object.entries(r.categories).map(([k, v]) => `${k}:${v}`).join(", ");
262
+ lines.push(` [FACT-GATE] ${r.ruleId}: ${r.downgrades} downgrade(s) (${cats || "other"})`);
263
+ }
264
+ for (const dt of signals.verifyHotspots.droppedFactTypes) {
265
+ anySignal = true;
266
+ lines.push(` [VERIFY-DROP] ${dt.type}: ${dt.count}`);
267
+ }
268
+ for (const reg of signals.verifyHotspots.regressionIds) {
269
+ anySignal = true;
270
+ lines.push(` [VERIFY-REG] ${reg.id}: ${reg.count}`);
271
+ }
272
+ for (const sf of signals.slowFiles.slice(0, 5)) {
273
+ anySignal = true;
274
+ lines.push(` [SLOW-FILE] ${sf.file} (${sf.ext}, ${sf.engine}): ${sf.durationMs}ms`);
275
+ }
276
+ if (signals.routingFriction.recommendation) {
277
+ anySignal = true;
278
+ lines.push(` [ROUTING] ${signals.routingFriction.recommendation}`);
279
+ }
280
+
281
+ if (!anySignal) {
282
+ lines.push(" (No optimization anomalies detected in the current window.)");
283
+ }
284
+ return `${lines.join("\n")}\n`;
285
+ }
286
+
287
+ /**
288
+ * `dislop worklog <status|list|show|stats|reflect|clear> [options]`
289
+ */
290
+ export async function runWorklogCommand(positionals, flags, io = {}) {
291
+ const { cwd = process.cwd(), env = process.env, stdout = process.stdout } = io;
292
+ const config = resolveLayeredConfig({ cwd, env, cliFlags: flags });
293
+ const subcommand = positionals[0] || "status";
294
+ const dir = config.worklog.dir;
295
+ const wantJson = Boolean(flags.json || flags.format === "json");
296
+
297
+ if (subcommand === "status") {
298
+ const storage = getWorklogStorageStats(dir);
299
+ const payload = {
300
+ schema: "dislop.worklog.status/1",
301
+ enabled: config.worklog.enabled,
302
+ active: isWorklogActive(config, env),
303
+ ciDisabled: isCiEnvironment(env),
304
+ privacy: config.worklog.privacy,
305
+ dir,
306
+ retentionDays: config.worklog.retentionDays,
307
+ fileCount: storage.fileCount,
308
+ entryCount: storage.entryCount,
309
+ totalBytes: storage.totalBytes,
310
+ };
311
+ stdout.write(wantJson ? `${JSON.stringify(payload, null, 2)}\n` : renderStatusText(payload));
312
+ return 0;
313
+ }
314
+
315
+ if (subcommand === "list") {
316
+ const days =
317
+ flags.days !== null && flags.days !== undefined
318
+ ? parseBoundedInt(flags.days, "--days", 1, 3650)
319
+ : 14;
320
+ const limit =
321
+ flags.limit !== null && flags.limit !== undefined
322
+ ? parseBoundedInt(flags.limit, "--limit", 1, 1000)
323
+ : 20;
324
+ const command = flags.command ? String(flags.command).trim() : null;
325
+ const entries = readWorklogEntries(dir, { days, command, limit });
326
+ if (wantJson) {
327
+ stdout.write(
328
+ `${JSON.stringify({ schema: "dislop.worklog.list/1", windowDays: days, count: entries.length, entries }, null, 2)}\n`,
329
+ );
330
+ } else {
331
+ stdout.write(renderListText(entries, days));
332
+ }
333
+ return 0;
334
+ }
335
+
336
+ if (subcommand === "show") {
337
+ const targetId = positionals[1];
338
+ if (!targetId) {
339
+ throw new DislopConfigError("Usage: dislop worklog show <id>");
340
+ }
341
+ const found = findWorklogEntryById(dir, targetId);
342
+ if (found.ambiguous) {
343
+ throw new DislopConfigError(
344
+ `Worklog id prefix '${targetId}' matched ${found.count} entries; provide a longer prefix.`,
345
+ );
346
+ }
347
+ if (!found.entry) {
348
+ throw new DislopConfigError(`Worklog entry not found: '${targetId}'`);
349
+ }
350
+ stdout.write(
351
+ wantJson ? `${JSON.stringify(found.entry, null, 2)}\n` : renderEntryDetailText(found.entry),
352
+ );
353
+ return 0;
354
+ }
355
+
356
+ if (subcommand === "stats") {
357
+ const days =
358
+ flags.days !== null && flags.days !== undefined
359
+ ? parseBoundedInt(flags.days, "--days", 1, 3650)
360
+ : 30;
361
+ const command = flags.command ? String(flags.command).trim() : null;
362
+ const entries = readWorklogEntries(dir, { days, command });
363
+ const stats = computeWorklogStats(entries);
364
+ if (wantJson) {
365
+ stdout.write(
366
+ `${JSON.stringify({ schema: "dislop.worklog.stats/1", windowDays: days, ...stats }, null, 2)}\n`,
367
+ );
368
+ } else {
369
+ stdout.write(renderStatsText(stats, days));
370
+ }
371
+ return 0;
372
+ }
373
+
374
+ if (subcommand === "reflect") {
375
+ const days =
376
+ flags.days !== null && flags.days !== undefined
377
+ ? parseBoundedInt(flags.days, "--days", 1, 3650)
378
+ : 30;
379
+ const format = flags.json ? "json" : flags.format || "text";
380
+ if (!["text", "markdown", "json"].includes(format)) {
381
+ throw new DislopConfigError(
382
+ `Invalid --format '${format}' for worklog reflect (expected text, markdown, or json)`,
383
+ );
384
+ }
385
+ const command = flags.command ? String(flags.command).trim() : null;
386
+ const entries = readWorklogEntries(dir, { days, command });
387
+ const report = buildReflectionReport(entries, { days });
388
+ if (format === "json") {
389
+ stdout.write(`${JSON.stringify(report, null, 2)}\n`);
390
+ } else if (format === "markdown") {
391
+ stdout.write(renderReflectMarkdown(report));
392
+ } else {
393
+ stdout.write(renderReflectText(report));
394
+ }
395
+ return 0;
396
+ }
397
+
398
+ if (subcommand === "clear") {
399
+ const olderThan =
400
+ flags.olderThan !== null && flags.olderThan !== undefined
401
+ ? parseBoundedInt(flags.olderThan, "--older-than", 1, 3650)
402
+ : null;
403
+ if (olderThan === null && !flags.yes && !flags.auto && !flags.force) {
404
+ throw new DislopConfigError(
405
+ "Refusing to delete all worklog entries without confirmation. Pass '--yes' (or '--older-than <days>') to proceed.",
406
+ );
407
+ }
408
+ const cleared = clearWorklogEntries(dir, { olderThanDays: olderThan });
409
+ if (wantJson) {
410
+ stdout.write(
411
+ `${JSON.stringify({ schema: "dislop.worklog.clear/1", olderThanDays: olderThan, ...cleared }, null, 2)}\n`,
412
+ );
413
+ } else {
414
+ stdout.write(
415
+ `Cleared ${cleared.removedEntries} entry(ies) across ${cleared.removedFiles} file(s) from ${dir}.\n`,
416
+ );
417
+ }
418
+ return 0;
419
+ }
420
+
421
+ throw new DislopConfigError(
422
+ `Unknown worklog subcommand '${subcommand}' (expected status, list, show, stats, reflect, or clear).`,
423
+ );
424
+ }