dislop 1.0.1 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) 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/action.yml +17 -2
  9. package/gemini-extension.json +1 -1
  10. package/package.json +2 -2
  11. package/packs/common/artifact-qa/scripts/index.mjs +64 -2
  12. package/packs/en/artifact-qa/scripts/index.mjs +1 -1
  13. package/packs/en/prose/scripts/index.mjs +3 -0
  14. package/plugin.json +1 -1
  15. package/server.json +2 -2
  16. package/skills/dislop/SKILL.md +1 -1
  17. package/skills/dislop/agents/openai.yaml +1 -1
  18. package/skills/dislop/references/essay.md +5 -5
  19. package/skills/dislop/references/essay.zh-CN.md +5 -5
  20. package/skills/dislop/references/office.md +4 -4
  21. package/skills/dislop/references/office.zh-CN.md +4 -4
  22. package/skills/dislop/references/web-ui.md +4 -4
  23. package/skills/dislop/references/web-ui.zh-CN.md +4 -4
  24. package/skills/dislop/references/work-docs.md +6 -6
  25. package/skills/dislop/references/work-docs.zh-CN.md +6 -6
  26. package/src/cli-main.mjs +88 -6
  27. package/src/commands/check-fix.mjs +170 -15
  28. package/src/commands/doctor.mjs +23 -1
  29. package/src/commands/init.mjs +24 -18
  30. package/src/commands/packs.mjs +41 -4
  31. package/src/commands/verify.mjs +36 -4
  32. package/src/commands/voice.mjs +1 -1
  33. package/src/commands/worklog.mjs +424 -0
  34. package/src/kernel/config.mjs +546 -19
  35. package/src/kernel/document-model.mjs +30 -10
  36. package/src/kernel/fact-gate.mjs +160 -0
  37. package/src/kernel/file-discovery.mjs +168 -11
  38. package/src/kernel/ooxml-binary.mjs +86 -0
  39. package/src/kernel/pack-loader.mjs +107 -21
  40. package/src/kernel/pack-validator.mjs +491 -0
  41. package/src/kernel/patcher.mjs +177 -47
  42. package/src/kernel/pipeline.mjs +284 -21
  43. package/src/kernel/prompt-assembler.mjs +37 -8
  44. package/src/kernel/version.mjs +7 -0
  45. package/src/kernel/voice-profile.mjs +3 -0
  46. package/src/mcp/stdio-server.mjs +71 -1
  47. package/src/runners/auto-fix.mjs +17 -2
  48. package/src/runners/interactive-tty.mjs +32 -5
  49. package/src/runners/reporters.mjs +18 -2
  50. package/src/runtime/providers/cloud.mjs +4 -2
  51. package/src/runtime/providers/local-model.mjs +8 -0
  52. package/src/runtime/router.mjs +11 -2
  53. package/src/runtime/worklog.mjs +904 -0
@@ -0,0 +1,904 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { isCiEnvironment } from "../kernel/config.mjs";
5
+ import { DISLOP_VERSION } from "../kernel/version.mjs";
6
+
7
+ const DAILY_FILE_RE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/;
8
+
9
+ function sha256Short(value) {
10
+ return crypto.createHash("sha256").update(String(value || "")).digest("hex").slice(0, 12);
11
+ }
12
+
13
+ function formatUtcDate(date = new Date()) {
14
+ return date.toISOString().slice(0, 10);
15
+ }
16
+
17
+ function parseUtcDayMs(dayStr) {
18
+ const m = String(dayStr || "").match(/^(\d{4})-(\d{2})-(\d{2})$/);
19
+ if (!m) return null;
20
+ return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
21
+ }
22
+
23
+ export function isWorklogActive(config, env = process.env) {
24
+ return Boolean(config?.worklog?.enabled && !isCiEnvironment(env));
25
+ }
26
+
27
+ /**
28
+ * Scrub credentials, API keys, bearer tokens, private keys, and URL auth tokens.
29
+ */
30
+ export function scrubSecrets(text) {
31
+ let out = String(text || "");
32
+ if (!out) return "";
33
+
34
+ out = out.replace(
35
+ /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
36
+ "[REDACTED_PRIVATE_KEY]",
37
+ );
38
+ out = out.replace(/\bdslp_[A-Za-z0-9._-]{4,}\b/g, "[REDACTED_TOKEN]");
39
+ out = out.replace(/\bsk-ant-[A-Za-z0-9_-]{8,}\b/g, "[REDACTED_KEY]");
40
+ out = out.replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED_KEY]");
41
+ out = out.replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{12,}\b/g, "[REDACTED_TOKEN]");
42
+ out = out.replace(/\bgithub_pat_[A-Za-z0-9_]{12,}\b/g, "[REDACTED_TOKEN]");
43
+ out = out.replace(/\bAIza[0-9A-Za-z_-]{16,}\b/g, "[REDACTED_KEY]");
44
+ out = out.replace(/\bAKIA[0-9A-Z]{12,}\b/g, "[REDACTED_KEY]");
45
+ out = out.replace(/\bBearer\s+[A-Za-z0-9._~+/-]{6,}=*/gi, "Bearer [REDACTED]");
46
+ out = out.replace(/(https?:\/\/)([^/\s:@]+):([^@\s/]+)@/gi, "$1[REDACTED]@");
47
+ out = out.replace(
48
+ /([?&#](?:token|key|api_key|apikey|secret|password|sig|signature)=)[^&\s#"']+/gi,
49
+ "$1[REDACTED]",
50
+ );
51
+
52
+ return out;
53
+ }
54
+
55
+ function maskHomeDirectories(text) {
56
+ return String(text || "")
57
+ .replace(/\/Users\/[^/\s"'`]+/g, "[HOME]")
58
+ .replace(/\/home\/[^/\s"'`]+/g, "[HOME]")
59
+ .replace(/[A-Za-z]:\\Users\\[^\\\s"'`]+/g, "[HOME]");
60
+ }
61
+
62
+ function truncateClean(text, maxLen) {
63
+ const collapsed = String(text || "").replace(/\s+/g, " ").trim();
64
+ if (!maxLen || collapsed.length <= maxLen) return collapsed;
65
+ if (maxLen <= 3) return collapsed.slice(0, maxLen);
66
+ return `${collapsed.slice(0, maxLen - 3)}...`;
67
+ }
68
+
69
+ /**
70
+ * Redact secrets, emails, URLs, home directory paths, and long numeric IDs,
71
+ * then collapse whitespace and truncate to `maxLen`.
72
+ */
73
+ export function redactText(text, maxLen = 160) {
74
+ let out = String(text || "");
75
+ out = out.replace(/\bhttps?:\/\/[^\s)>\]"']+/gi, "[URL]");
76
+ out = scrubSecrets(out);
77
+ out = out.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[EMAIL]");
78
+ out = maskHomeDirectories(out);
79
+ out = out.replace(/\b\d{6,}\b/g, "[NUM_ID]");
80
+ return truncateClean(out, maxLen);
81
+ }
82
+
83
+ function scrubTextForLocalFull(text, maxLen = 400) {
84
+ const scrubbed = maskHomeDirectories(scrubSecrets(text));
85
+ return truncateClean(scrubbed, maxLen);
86
+ }
87
+
88
+ /**
89
+ * Map Fact Gate human-readable reasons into coarse privacy-safe categories.
90
+ */
91
+ export function classifyFactGateReasons(reasons) {
92
+ const categories = new Set();
93
+ for (const raw of reasons || []) {
94
+ const r = String(raw || "").toLowerCase();
95
+ if (!r) continue;
96
+ if (r.includes("dropped number")) categories.add("dropped_number");
97
+ else if (r.includes("dropped unit")) categories.add("dropped_unit");
98
+ else if (r.includes("dropped url")) categories.add("dropped_url");
99
+ else if (r.includes("dropped inline code")) categories.add("dropped_code");
100
+ else if (r.includes("dropped proper noun")) categories.add("dropped_entity");
101
+ else if (r.includes("injected unverified url")) categories.add("injected_url");
102
+ else if (r.includes("injected unverified inline code")) categories.add("injected_code");
103
+ else if (r.includes("fabricated number")) categories.add("fabricated_number");
104
+ else if (r.includes("pack_verify_fix") || r.includes("failed custom verifyfix") || r.includes("pack '")) {
105
+ categories.add("pack_verify_fix");
106
+ } else {
107
+ categories.add("other");
108
+ }
109
+ }
110
+ return Array.from(categories);
111
+ }
112
+
113
+ export function classifyFactGateNote(note) {
114
+ if (!note) return [];
115
+ const raw = String(note);
116
+ const parenMatch = raw.match(/\(([^)]+)\)\.?$/);
117
+ const inner = parenMatch ? parenMatch[1] : raw;
118
+ const parts = inner.split(/;\s*/).filter(Boolean);
119
+ return classifyFactGateReasons(parts.length > 0 ? parts : [raw]);
120
+ }
121
+
122
+ /**
123
+ * Sanitize target file path according to privacy tier.
124
+ * - `metadata`: returns `{ fileHash, ext }` only (zero path/filename exposure).
125
+ * - `redacted` / `local-full`: adds relative `fileRef` inside `cwd`, or `<external>/<fileHash>.<ext>` outside `cwd`.
126
+ */
127
+ export function sanitizeFileTarget(filePath, cwd = process.cwd(), privacy = "metadata") {
128
+ const rawPath = String(filePath || "unknown");
129
+ const resolvedCwd = path.resolve(cwd);
130
+ const resolvedTarget = path.resolve(resolvedCwd, rawPath);
131
+ const ext = path.extname(rawPath).replace(/^\./, "").toLowerCase() || "unknown";
132
+ const fileHash = sha256Short(resolvedTarget);
133
+
134
+ if (privacy === "metadata") {
135
+ return { fileHash, ext };
136
+ }
137
+
138
+ const rel = path.relative(resolvedCwd, resolvedTarget);
139
+ const insideCwd =
140
+ rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
141
+ let fileRef;
142
+ if (insideCwd) {
143
+ const cleanRel = (rel || path.basename(resolvedTarget)).replace(/\\/g, "/");
144
+ fileRef = maskHomeDirectories(cleanRel);
145
+ } else {
146
+ fileRef = `<external>/${fileHash}.${ext}`;
147
+ }
148
+
149
+ return { fileHash, ext, fileRef };
150
+ }
151
+
152
+ function resolveFileDecisionMeta(decisionsByFile, index, res) {
153
+ if (!decisionsByFile) return { decisions: {}, undoCount: 0, aborted: false };
154
+ if (Array.isArray(decisionsByFile)) {
155
+ return decisionsByFile[index] || { decisions: {}, undoCount: 0, aborted: false };
156
+ }
157
+ if (decisionsByFile instanceof Map) {
158
+ return (
159
+ decisionsByFile.get(res?.doc?.filePath) ||
160
+ decisionsByFile.get(res?.report?.file) ||
161
+ decisionsByFile.get(index) ||
162
+ { decisions: {}, undoCount: 0, aborted: false }
163
+ );
164
+ }
165
+ const key = res?.doc?.filePath || res?.report?.file;
166
+ return decisionsByFile[key] || decisionsByFile[index] || { decisions: {}, undoCount: 0, aborted: false };
167
+ }
168
+
169
+ export function buildCheckOrFixWorklogEntry({
170
+ source = "cli",
171
+ command,
172
+ mode = null,
173
+ cwd = process.cwd(),
174
+ config,
175
+ route = null,
176
+ results = [],
177
+ decisionsByFile = null,
178
+ durationMs = 0,
179
+ exitCode = 0,
180
+ aborted = false,
181
+ now = new Date(),
182
+ } = {}) {
183
+ const privacy = config?.worklog?.privacy || "metadata";
184
+ const resolvedCwd = path.resolve(cwd);
185
+ const workspaceHash = sha256Short(resolvedCwd);
186
+
187
+ const summary = {
188
+ defects: { error: 0, warning: 0 },
189
+ suggestions: { strong: 0, moderate: 0, hint: 0 },
190
+ applied: 0,
191
+ skipped: 0,
192
+ edited: 0,
193
+ promptCopied: 0,
194
+ undoCount: 0,
195
+ factGateDowngraded: 0,
196
+ aborted: Boolean(aborted),
197
+ };
198
+
199
+ let routeFallback = false;
200
+ let observedEngine = route?.engineLabel || null;
201
+ const files = [];
202
+
203
+ for (let i = 0; i < results.length; i += 1) {
204
+ const res = results[i] || {};
205
+ const doc = res.doc || {};
206
+ const report = res.report || {};
207
+ const items = Array.isArray(res.items) ? res.items : Array.isArray(report.items) ? report.items : [];
208
+ const fileMeta = resolveFileDecisionMeta(decisionsByFile, i, res);
209
+ const decisionsMap = fileMeta.decisions || {};
210
+
211
+ if (fileMeta.undoCount) summary.undoCount += fileMeta.undoCount;
212
+ if (fileMeta.aborted) summary.aborted = true;
213
+ if (res.routeFallback || res.routeHint) routeFallback = true;
214
+ if (report.engine && (!observedEngine || report.engine !== "deterministic")) {
215
+ observedEngine = report.engine;
216
+ }
217
+
218
+ const targetInfo = sanitizeFileTarget(doc.filePath || report.file || "unknown", resolvedCwd, privacy);
219
+ const findings = [];
220
+
221
+ for (const item of items) {
222
+ if (item.kind === "defect") {
223
+ if (item.severity === "error") summary.defects.error += 1;
224
+ else summary.defects.warning += 1;
225
+ } else if (item.kind === "suggestion") {
226
+ if (item.priority === "strong") summary.suggestions.strong += 1;
227
+ else if (item.priority === "hint") summary.suggestions.hint += 1;
228
+ else summary.suggestions.moderate += 1;
229
+ }
230
+
231
+ const decision = decisionsMap[item.id] || null;
232
+ if (decision === "auto_applied" || decision === "accepted") summary.applied += 1;
233
+ else if (decision === "edited") {
234
+ summary.applied += 1;
235
+ summary.edited += 1;
236
+ } else if (decision === "prompt_copied") {
237
+ summary.promptCopied += 1;
238
+ summary.skipped += 1;
239
+ } else if (decision === "skipped") {
240
+ summary.skipped += 1;
241
+ }
242
+
243
+ const downgraded = Boolean(item._factGateDowngraded || (item.verificationNote && /withheld/i.test(item.verificationNote)));
244
+ if (downgraded) summary.factGateDowngraded += 1;
245
+
246
+ const factGateCategories = downgraded
247
+ ? item._factGateReasons
248
+ ? classifyFactGateReasons(item._factGateReasons)
249
+ : classifyFactGateNote(item.verificationNote)
250
+ : [];
251
+
252
+ const findingEntry = {
253
+ ruleId: item.ruleId,
254
+ pack: item.pack,
255
+ kind: item.kind,
256
+ severityOrPriority: item.kind === "defect" ? item.severity || "error" : item.priority || "moderate",
257
+ origin: item._source === "llm" ? "llm" : "deterministic",
258
+ fixSafety: item.fixSafety,
259
+ actionType: item.actionType,
260
+ decision,
261
+ factGateDowngraded: downgraded,
262
+ ...(factGateCategories.length > 0 ? { factGateCategories } : {}),
263
+ };
264
+
265
+ if (privacy === "redacted") {
266
+ if (item.originalQuote) findingEntry.quotePreview = redactText(item.originalQuote, 160);
267
+ if (item.suggestedReplacement) {
268
+ findingEntry.replacementPreview = redactText(item.suggestedReplacement, 160);
269
+ }
270
+ if (item.verificationNote) {
271
+ findingEntry.verificationNotePreview = redactText(item.verificationNote, 160);
272
+ }
273
+ } else if (privacy === "local-full") {
274
+ if (item.originalQuote) findingEntry.originalQuote = scrubTextForLocalFull(item.originalQuote, 400);
275
+ if (item.suggestedReplacement) {
276
+ findingEntry.suggestedReplacement = scrubTextForLocalFull(item.suggestedReplacement, 400);
277
+ }
278
+ if (item.reason) findingEntry.reason = scrubTextForLocalFull(item.reason, 400);
279
+ if (item.verificationNote) {
280
+ findingEntry.verificationNote = scrubTextForLocalFull(item.verificationNote, 400);
281
+ }
282
+ }
283
+
284
+ findings.push(findingEntry);
285
+ }
286
+
287
+ files.push({
288
+ ...targetInfo,
289
+ language: doc.language || report.language || "unknown",
290
+ modality: doc.modality || "unknown",
291
+ segmentCount: Array.isArray(doc.segments) ? doc.segments.length : 0,
292
+ engine: report.engine || observedEngine || "deterministic",
293
+ durationMs: Number.isFinite(res.durationMs) ? res.durationMs : null,
294
+ mountedPacks: Array.isArray(report.mountedPacks) ? report.mountedPacks : [],
295
+ findings,
296
+ });
297
+ }
298
+
299
+ return {
300
+ schema: "dislop.worklog/1",
301
+ id: crypto.randomUUID(),
302
+ timestamp: now.toISOString(),
303
+ version: DISLOP_VERSION,
304
+ privacy,
305
+ source,
306
+ command,
307
+ mode,
308
+ workspaceHash,
309
+ ...(privacy !== "metadata" ? { workspaceName: path.basename(resolvedCwd) || "workspace" } : {}),
310
+ durationMs: Math.max(0, Math.round(durationMs)),
311
+ exitCode,
312
+ routing: config?.routing || "local",
313
+ engine: observedEngine || "deterministic",
314
+ routeFallback,
315
+ fileCount: files.length,
316
+ summary,
317
+ files,
318
+ verify: null,
319
+ };
320
+ }
321
+
322
+ export function buildVerifyWorklogEntry({
323
+ source = "cli",
324
+ command = "verify",
325
+ mode = "verify",
326
+ cwd = process.cwd(),
327
+ config,
328
+ targetLabel = "",
329
+ verification,
330
+ durationMs = 0,
331
+ exitCode = 0,
332
+ now = new Date(),
333
+ } = {}) {
334
+ const privacy = config?.worklog?.privacy || "metadata";
335
+ const resolvedCwd = path.resolve(cwd);
336
+ const workspaceHash = sha256Short(resolvedCwd);
337
+ const droppedFacts = Array.isArray(verification?.droppedFacts) ? verification.droppedFacts : [];
338
+ const regressions = Array.isArray(verification?.regressions) ? verification.regressions : [];
339
+
340
+ const verifyPayload = {
341
+ ok: Boolean(verification?.ok),
342
+ droppedFactsCount: droppedFacts.length,
343
+ droppedFactTypes: classifyFactGateReasons(droppedFacts),
344
+ regressionIds: regressions.map((r) => r?.id).filter(Boolean),
345
+ };
346
+
347
+ if (privacy === "redacted") {
348
+ verifyPayload.targetPreview = redactText(targetLabel, 120);
349
+ verifyPayload.droppedFacts = droppedFacts.map((r) => redactText(r, 160));
350
+ verifyPayload.regressions = regressions.map((r) => ({
351
+ id: r?.id || "unknown",
352
+ message: redactText(r?.message || "", 160),
353
+ }));
354
+ } else if (privacy === "local-full") {
355
+ verifyPayload.targetLabel = scrubTextForLocalFull(targetLabel, 240);
356
+ verifyPayload.droppedFacts = droppedFacts.map((r) => scrubTextForLocalFull(r, 400));
357
+ verifyPayload.regressions = regressions.map((r) => ({
358
+ id: r?.id || "unknown",
359
+ message: scrubTextForLocalFull(r?.message || "", 400),
360
+ }));
361
+ }
362
+
363
+ return {
364
+ schema: "dislop.worklog/1",
365
+ id: crypto.randomUUID(),
366
+ timestamp: now.toISOString(),
367
+ version: DISLOP_VERSION,
368
+ privacy,
369
+ source,
370
+ command,
371
+ mode,
372
+ workspaceHash,
373
+ ...(privacy !== "metadata" ? { workspaceName: path.basename(resolvedCwd) || "workspace" } : {}),
374
+ durationMs: Math.max(0, Math.round(durationMs)),
375
+ exitCode,
376
+ routing: config?.routing || "local",
377
+ engine: "deterministic",
378
+ routeFallback: false,
379
+ fileCount: 0,
380
+ summary: {
381
+ defects: { error: 0, warning: 0 },
382
+ suggestions: { strong: 0, moderate: 0, hint: 0 },
383
+ applied: 0,
384
+ skipped: 0,
385
+ edited: 0,
386
+ promptCopied: 0,
387
+ undoCount: 0,
388
+ factGateDowngraded: 0,
389
+ aborted: false,
390
+ },
391
+ files: [],
392
+ verify: verifyPayload,
393
+ };
394
+ }
395
+
396
+ /**
397
+ * Remove daily `YYYY-MM-DD.jsonl` files strictly older than `retentionDays`.
398
+ */
399
+ export function pruneExpiredWorklogs(dir, retentionDays, now = new Date()) {
400
+ if (!dir || !fs.existsSync(dir)) return 0;
401
+ const days = Math.max(1, Number(retentionDays) || 30);
402
+ const todayUtcMs = parseUtcDayMs(formatUtcDate(now));
403
+ const maxAgeMs = (days - 1) * 86400000;
404
+ let removed = 0;
405
+
406
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
407
+ if (!entry.isFile()) continue;
408
+ const m = entry.name.match(DAILY_FILE_RE);
409
+ if (!m) continue;
410
+ const fileDayMs = parseUtcDayMs(m[1]);
411
+ if (fileDayMs === null) continue;
412
+ if (todayUtcMs - fileDayMs > maxAgeMs) {
413
+ try {
414
+ fs.unlinkSync(path.join(dir, entry.name));
415
+ removed += 1;
416
+ } catch {
417
+ // best-effort prune
418
+ }
419
+ }
420
+ }
421
+ return removed;
422
+ }
423
+
424
+ /**
425
+ * Best-effort non-fatal append to the local daily worklog JSONL file.
426
+ * Never throws and never writes to stdout or stderr.
427
+ */
428
+ export function recordWorklogEntry(entry, config, env = process.env, now = new Date()) {
429
+ if (!entry || !isWorklogActive(config, env)) {
430
+ return { written: false };
431
+ }
432
+ const dir = config?.worklog?.dir;
433
+ if (!dir) return { written: false };
434
+
435
+ try {
436
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
437
+ try {
438
+ fs.chmodSync(dir, 0o700);
439
+ } catch {
440
+ // ignore chmod errors on unsupported filesystems
441
+ }
442
+
443
+ const fileName = `${formatUtcDate(now)}.jsonl`;
444
+ const filePath = path.join(dir, fileName);
445
+ const line = `${JSON.stringify(entry)}\n`;
446
+ fs.appendFileSync(filePath, line, { encoding: "utf8", mode: 0o600 });
447
+ try {
448
+ fs.chmodSync(filePath, 0o600);
449
+ } catch {
450
+ // ignore chmod errors on unsupported filesystems
451
+ }
452
+
453
+ pruneExpiredWorklogs(dir, config.worklog.retentionDays, now);
454
+ return { written: true, filePath };
455
+ } catch {
456
+ return { written: false };
457
+ }
458
+ }
459
+
460
+ export function getWorklogStorageStats(dir) {
461
+ if (!dir || !fs.existsSync(dir)) {
462
+ return { fileCount: 0, entryCount: 0, totalBytes: 0, files: [] };
463
+ }
464
+
465
+ let fileCount = 0;
466
+ let entryCount = 0;
467
+ let totalBytes = 0;
468
+ const files = [];
469
+
470
+ let entries = [];
471
+ try {
472
+ entries = fs.readdirSync(dir, { withFileTypes: true });
473
+ } catch {
474
+ return { fileCount: 0, entryCount: 0, totalBytes: 0, files: [] };
475
+ }
476
+
477
+ for (const entry of entries) {
478
+ if (!entry.isFile() || !DAILY_FILE_RE.test(entry.name)) continue;
479
+ const full = path.join(dir, entry.name);
480
+ try {
481
+ const stat = fs.statSync(full);
482
+ const raw = fs.readFileSync(full, "utf8");
483
+ let validLines = 0;
484
+ for (const line of raw.split("\n")) {
485
+ const trimmed = line.trim();
486
+ if (!trimmed) continue;
487
+ try {
488
+ const parsed = JSON.parse(trimmed);
489
+ if (parsed && typeof parsed === "object") validLines += 1;
490
+ } catch {
491
+ // ignore malformed JSONL line
492
+ }
493
+ }
494
+ fileCount += 1;
495
+ entryCount += validLines;
496
+ totalBytes += stat.size;
497
+ files.push({ name: entry.name, entries: validLines, bytes: stat.size });
498
+ } catch {
499
+ // skip unreadable file
500
+ }
501
+ }
502
+
503
+ files.sort((a, b) => b.name.localeCompare(a.name));
504
+ return { fileCount, entryCount, totalBytes, files };
505
+ }
506
+
507
+ export function readWorklogEntries(
508
+ dir,
509
+ { days = 30, command = null, limit = null, now = new Date() } = {},
510
+ ) {
511
+ if (!dir || !fs.existsSync(dir)) return [];
512
+
513
+ const daysWindow = days !== null && days !== undefined ? Math.max(1, Number(days) || 30) : null;
514
+ const todayUtcMs = parseUtcDayMs(formatUtcDate(now));
515
+ const cutoffMs = daysWindow ? todayUtcMs - (daysWindow - 1) * 86400000 : null;
516
+
517
+ let dirEntries = [];
518
+ try {
519
+ dirEntries = fs.readdirSync(dir, { withFileTypes: true });
520
+ } catch {
521
+ return [];
522
+ }
523
+
524
+ const matchedFiles = dirEntries
525
+ .filter((e) => e.isFile())
526
+ .map((e) => {
527
+ const m = e.name.match(DAILY_FILE_RE);
528
+ return m ? { name: e.name, dayMs: parseUtcDayMs(m[1]) } : null;
529
+ })
530
+ .filter((f) => f && f.dayMs !== null && (cutoffMs === null || f.dayMs >= cutoffMs))
531
+ .sort((a, b) => b.name.localeCompare(a.name));
532
+
533
+ const parsed = [];
534
+ for (const f of matchedFiles) {
535
+ let raw;
536
+ try {
537
+ raw = fs.readFileSync(path.join(dir, f.name), "utf8");
538
+ } catch {
539
+ continue;
540
+ }
541
+ const lines = raw.split("\n");
542
+ for (const line of lines) {
543
+ const trimmed = line.trim();
544
+ if (!trimmed) continue;
545
+ try {
546
+ const obj = JSON.parse(trimmed);
547
+ if (!obj || typeof obj !== "object") continue;
548
+ if (command && obj.command !== command) continue;
549
+ parsed.push(obj);
550
+ } catch {
551
+ // Ignore malformed JSONL line gracefully
552
+ }
553
+ }
554
+ }
555
+
556
+ parsed.sort((a, b) => String(b.timestamp || "").localeCompare(String(a.timestamp || "")));
557
+ if (limit && limit > 0) {
558
+ return parsed.slice(0, limit);
559
+ }
560
+ return parsed;
561
+ }
562
+
563
+ export function findWorklogEntryById(dir, idQuery) {
564
+ const query = String(idQuery || "").trim();
565
+ if (!query) return { entry: null, ambiguous: false };
566
+ const all = readWorklogEntries(dir, { days: null });
567
+ const exact = all.find((e) => e.id === query);
568
+ if (exact) return { entry: exact, ambiguous: false };
569
+
570
+ const prefixMatches = all.filter((e) => typeof e.id === "string" && e.id.startsWith(query));
571
+ if (prefixMatches.length === 1) return { entry: prefixMatches[0], ambiguous: false };
572
+ if (prefixMatches.length > 1) return { entry: null, ambiguous: true, count: prefixMatches.length };
573
+ return { entry: null, ambiguous: false };
574
+ }
575
+
576
+ export function clearWorklogEntries(dir, { olderThanDays = null, now = new Date() } = {}) {
577
+ if (!dir || !fs.existsSync(dir)) {
578
+ return { removedFiles: 0, removedEntries: 0 };
579
+ }
580
+
581
+ const todayUtcMs = parseUtcDayMs(formatUtcDate(now));
582
+ const cutoffMs =
583
+ olderThanDays !== null && olderThanDays !== undefined
584
+ ? todayUtcMs - (Math.max(1, Number(olderThanDays)) - 1) * 86400000
585
+ : null;
586
+
587
+ let removedFiles = 0;
588
+ let removedEntries = 0;
589
+
590
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
591
+ if (!entry.isFile()) continue;
592
+ const m = entry.name.match(DAILY_FILE_RE);
593
+ if (!m) continue;
594
+ const dayMs = parseUtcDayMs(m[1]);
595
+ if (dayMs === null) continue;
596
+ if (cutoffMs !== null && dayMs >= cutoffMs) continue;
597
+
598
+ const full = path.join(dir, entry.name);
599
+ try {
600
+ const raw = fs.readFileSync(full, "utf8");
601
+ const lineCount = raw.split("\n").filter((l) => l.trim().length > 0).length;
602
+ fs.unlinkSync(full);
603
+ removedFiles += 1;
604
+ removedEntries += lineCount;
605
+ } catch {
606
+ // best-effort delete
607
+ }
608
+ }
609
+
610
+ return { removedFiles, removedEntries };
611
+ }
612
+
613
+ function percentile(sortedNums, p) {
614
+ if (!sortedNums || sortedNums.length === 0) return 0;
615
+ const idx = Math.min(sortedNums.length - 1, Math.max(0, Math.ceil(sortedNums.length * p) - 1));
616
+ return sortedNums[idx];
617
+ }
618
+
619
+ export function computeWorklogStats(entries = []) {
620
+ const byCommand = {};
621
+ const bySource = {};
622
+ const byEngine = {};
623
+ const byExitCode = {};
624
+ const durations = [];
625
+ const ruleMap = new Map();
626
+ const formatLatencies = new Map();
627
+
628
+ let fallbackRuns = 0;
629
+ let totalFiles = 0;
630
+ let totalDefectsError = 0;
631
+ let totalDefectsWarning = 0;
632
+ let totalSuggestionsStrong = 0;
633
+ let totalSuggestionsModerate = 0;
634
+ let totalSuggestionsHint = 0;
635
+ let totalApplied = 0;
636
+ let totalSkipped = 0;
637
+ let totalEdited = 0;
638
+ let totalPromptCopied = 0;
639
+ let totalFactGateDowngraded = 0;
640
+
641
+ const verifyStats = {
642
+ total: 0,
643
+ passed: 0,
644
+ failed: 0,
645
+ droppedFactTypes: {},
646
+ regressionIds: {},
647
+ };
648
+
649
+ for (const entry of entries) {
650
+ const cmd = entry.command || "unknown";
651
+ const src = entry.source || "cli";
652
+ const eng = entry.engine || "deterministic";
653
+ const code = String(entry.exitCode ?? 0);
654
+
655
+ byCommand[cmd] = (byCommand[cmd] || 0) + 1;
656
+ bySource[src] = (bySource[src] || 0) + 1;
657
+ byEngine[eng] = (byEngine[eng] || 0) + 1;
658
+ byExitCode[code] = (byExitCode[code] || 0) + 1;
659
+
660
+ if (Number.isFinite(entry.durationMs)) {
661
+ durations.push(entry.durationMs);
662
+ }
663
+ if (entry.routeFallback) {
664
+ fallbackRuns += 1;
665
+ }
666
+
667
+ const s = entry.summary || {};
668
+ totalFiles += Number(entry.fileCount || 0);
669
+ totalDefectsError += Number(s.defects?.error || 0);
670
+ totalDefectsWarning += Number(s.defects?.warning || 0);
671
+ totalSuggestionsStrong += Number(s.suggestions?.strong || 0);
672
+ totalSuggestionsModerate += Number(s.suggestions?.moderate || 0);
673
+ totalSuggestionsHint += Number(s.suggestions?.hint || 0);
674
+ totalApplied += Number(s.applied || 0);
675
+ totalSkipped += Number(s.skipped || 0);
676
+ totalEdited += Number(s.edited || 0);
677
+ totalPromptCopied += Number(s.promptCopied || 0);
678
+ totalFactGateDowngraded += Number(s.factGateDowngraded || 0);
679
+
680
+ if (entry.verify) {
681
+ verifyStats.total += 1;
682
+ if (entry.verify.ok) verifyStats.passed += 1;
683
+ else verifyStats.failed += 1;
684
+
685
+ for (const dt of entry.verify.droppedFactTypes || []) {
686
+ verifyStats.droppedFactTypes[dt] = (verifyStats.droppedFactTypes[dt] || 0) + 1;
687
+ }
688
+ for (const rid of entry.verify.regressionIds || []) {
689
+ verifyStats.regressionIds[rid] = (verifyStats.regressionIds[rid] || 0) + 1;
690
+ }
691
+ }
692
+
693
+ for (const fileRec of entry.files || []) {
694
+ const ext = fileRec.ext || "unknown";
695
+ if (Number.isFinite(fileRec.durationMs)) {
696
+ if (!formatLatencies.has(ext)) {
697
+ formatLatencies.set(ext, []);
698
+ }
699
+ formatLatencies.get(ext).push(fileRec.durationMs);
700
+ }
701
+
702
+ for (const f of fileRec.findings || []) {
703
+ const rid = f.ruleId || "unknown";
704
+ if (!ruleMap.has(rid)) {
705
+ ruleMap.set(rid, {
706
+ ruleId: rid,
707
+ pack: f.pack || "unknown",
708
+ kind: f.kind || "suggestion",
709
+ hits: 0,
710
+ deterministicHits: 0,
711
+ llmHits: 0,
712
+ accepted: 0,
713
+ autoApplied: 0,
714
+ skipped: 0,
715
+ edited: 0,
716
+ promptCopied: 0,
717
+ factGateDowngrades: 0,
718
+ factGateCategories: {},
719
+ });
720
+ }
721
+ const rec = ruleMap.get(rid);
722
+ rec.hits += 1;
723
+ if (f.origin === "llm") rec.llmHits += 1;
724
+ else rec.deterministicHits += 1;
725
+
726
+ if (f.decision === "accepted") rec.accepted += 1;
727
+ else if (f.decision === "auto_applied") rec.autoApplied += 1;
728
+ else if (f.decision === "skipped") rec.skipped += 1;
729
+ else if (f.decision === "edited") rec.edited += 1;
730
+ else if (f.decision === "prompt_copied") {
731
+ rec.promptCopied += 1;
732
+ rec.skipped += 1;
733
+ }
734
+
735
+ if (f.factGateDowngraded) {
736
+ rec.factGateDowngrades += 1;
737
+ for (const cat of f.factGateCategories || []) {
738
+ rec.factGateCategories[cat] = (rec.factGateCategories[cat] || 0) + 1;
739
+ }
740
+ }
741
+ }
742
+ }
743
+ }
744
+
745
+ durations.sort((a, b) => a - b);
746
+
747
+ const rules = Array.from(ruleMap.values())
748
+ .map((r) => {
749
+ const interactiveDecisions = r.accepted + r.skipped + r.edited;
750
+ const skipRate = interactiveDecisions > 0 ? Number((r.skipped / interactiveDecisions).toFixed(3)) : null;
751
+ return {
752
+ ...r,
753
+ interactiveDecisions,
754
+ skipRate,
755
+ };
756
+ })
757
+ .sort((a, b) => b.hits - a.hits || a.ruleId.localeCompare(b.ruleId));
758
+
759
+ const latencyByFormat = {};
760
+ for (const [ext, list] of formatLatencies.entries()) {
761
+ const sorted = [...list].sort((a, b) => a - b);
762
+ latencyByFormat[ext] = {
763
+ files: sorted.length,
764
+ p50Ms: percentile(sorted, 0.5),
765
+ p95Ms: percentile(sorted, 0.95),
766
+ maxMs: sorted[sorted.length - 1] || 0,
767
+ };
768
+ }
769
+
770
+ return {
771
+ totalRuns: entries.length,
772
+ totalFiles,
773
+ byCommand,
774
+ bySource,
775
+ byEngine,
776
+ byExitCode,
777
+ fallbackRuns,
778
+ fallbackRate: entries.length > 0 ? Number((fallbackRuns / entries.length).toFixed(3)) : 0,
779
+ latency: {
780
+ p50Ms: percentile(durations, 0.5),
781
+ p95Ms: percentile(durations, 0.95),
782
+ maxMs: durations.length > 0 ? durations[durations.length - 1] : 0,
783
+ },
784
+ latencyByFormat,
785
+ findingsSummary: {
786
+ defects: { error: totalDefectsError, warning: totalDefectsWarning },
787
+ suggestions: {
788
+ strong: totalSuggestionsStrong,
789
+ moderate: totalSuggestionsModerate,
790
+ hint: totalSuggestionsHint,
791
+ },
792
+ applied: totalApplied,
793
+ skipped: totalSkipped,
794
+ edited: totalEdited,
795
+ promptCopied: totalPromptCopied,
796
+ factGateDowngraded: totalFactGateDowngraded,
797
+ },
798
+ verify: verifyStats,
799
+ rules,
800
+ };
801
+ }
802
+
803
+ /**
804
+ * Generate actionable optimization signals from local worklog entries.
805
+ */
806
+ export function buildReflectionReport(entries = [], { days = 30 } = {}) {
807
+ const stats = computeWorklogStats(entries);
808
+
809
+ const highSkipRules = stats.rules
810
+ .filter((r) => r.interactiveDecisions >= 3 && r.skipRate !== null && r.skipRate >= 0.5)
811
+ .sort((a, b) => b.skipRate - a.skipRate || b.skipped - a.skipped)
812
+ .map((r) => ({
813
+ ruleId: r.ruleId,
814
+ pack: r.pack,
815
+ hits: r.hits,
816
+ skipped: r.skipped,
817
+ interactiveDecisions: r.interactiveDecisions,
818
+ skipRate: r.skipRate,
819
+ recommendation:
820
+ "Review rule specificity or false-positive boundaries; users skipped >=50% of interactive hunks.",
821
+ }));
822
+
823
+ const highEditRules = stats.rules
824
+ .filter((r) => r.edited >= 2)
825
+ .sort((a, b) => b.edited - a.edited)
826
+ .map((r) => ({
827
+ ruleId: r.ruleId,
828
+ pack: r.pack,
829
+ edited: r.edited,
830
+ hits: r.hits,
831
+ recommendation:
832
+ "Users repeatedly edited this rule manually via $EDITOR; tighten suggestedReplacement or rewritePrompt.",
833
+ }));
834
+
835
+ const factGateHotspots = stats.rules
836
+ .filter((r) => r.factGateDowngrades > 0)
837
+ .sort((a, b) => b.factGateDowngrades - a.factGateDowngrades)
838
+ .map((r) => ({
839
+ ruleId: r.ruleId,
840
+ pack: r.pack,
841
+ downgrades: r.factGateDowngrades,
842
+ categories: r.factGateCategories,
843
+ recommendation:
844
+ "LLM/pack suggestions dropped or fabricated protected anchors; reinforce prompt preservation instructions.",
845
+ }));
846
+
847
+ const verifyHotspots = {
848
+ total: stats.verify.total,
849
+ failed: stats.verify.failed,
850
+ failRate:
851
+ stats.verify.total > 0 ? Number((stats.verify.failed / stats.verify.total).toFixed(3)) : 0,
852
+ droppedFactTypes: Object.entries(stats.verify.droppedFactTypes)
853
+ .map(([type, count]) => ({ type, count }))
854
+ .sort((a, b) => b.count - a.count),
855
+ regressionIds: Object.entries(stats.verify.regressionIds)
856
+ .map(([id, count]) => ({ id, count }))
857
+ .sort((a, b) => b.count - a.count),
858
+ };
859
+
860
+ const slowFiles = [];
861
+ for (const entry of entries) {
862
+ const isLlm = entry.engine && entry.engine !== "deterministic";
863
+ const thresholdMs = isLlm ? 5000 : 500;
864
+ for (const fileRec of entry.files || []) {
865
+ if (Number.isFinite(fileRec.durationMs) && fileRec.durationMs > thresholdMs) {
866
+ slowFiles.push({
867
+ entryId: entry.id,
868
+ timestamp: entry.timestamp,
869
+ file: fileRec.fileRef || `${fileRec.fileHash}.${fileRec.ext}`,
870
+ ext: fileRec.ext,
871
+ modality: fileRec.modality,
872
+ engine: fileRec.engine || entry.engine,
873
+ durationMs: fileRec.durationMs,
874
+ segmentCount: fileRec.segmentCount,
875
+ });
876
+ }
877
+ }
878
+ }
879
+ slowFiles.sort((a, b) => b.durationMs - a.durationMs);
880
+
881
+ const routingFriction = {
882
+ totalRuns: stats.totalRuns,
883
+ fallbackRuns: stats.fallbackRuns,
884
+ fallbackRate: stats.fallbackRate,
885
+ recommendation:
886
+ stats.fallbackRuns > 0
887
+ ? "Some runs fell back from LLM routing to deterministic mode; check Ollama or provider health with 'dislop doctor'."
888
+ : null,
889
+ };
890
+
891
+ return {
892
+ schema: "dislop.worklog.reflect/1",
893
+ windowDays: days,
894
+ stats,
895
+ signals: {
896
+ highSkipRules,
897
+ highEditRules,
898
+ factGateHotspots,
899
+ verifyHotspots,
900
+ slowFiles: slowFiles.slice(0, 20),
901
+ routingFriction,
902
+ },
903
+ };
904
+ }