unslop-core 1.0.0 → 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.
package/README.md CHANGED
@@ -67,3 +67,10 @@ Tool handlers return a plain object; set `_failed: true` to mark the MCP result
67
67
  ## License
68
68
 
69
69
  MIT © Fikri Firman Fadilah
70
+
71
+ ## Violation contract and telemetry (1.1)
72
+
73
+ Every finding now carries `rule_id` and `fix_hint` next to the existing fields. `rule` stays for existing skills.
74
+
75
+ - `fix_hint` comes from the rule's optional `fix` field. Without one, it is the rule's message after its first sentence ("Problem. Fix."). It is capped at 200 chars.
76
+ - When the workspace has a `.doctor-unslop/` directory, the audit tool appends one privacy-safe line per scanned file to `.doctor-unslop/telemetry.jsonl` for `doctor-unslop loops`. Without that directory, nothing is written.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unslop-core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Shared engine for the *-unslop-mcp servers: comment-aware regex/structural audits, suppressions, git-change discovery, toolchain checks, CLI mode and skill installer.",
5
5
  "type": "module",
6
6
  "main": "src/index.mjs",
package/src/audit.mjs CHANGED
@@ -111,6 +111,29 @@ export function matchRule(rule, raw, file) {
111
111
  return [...src.matchAll(globalize(rule.regex))].map((m) => ({ index: m.index, text: m[0] }));
112
112
  }
113
113
 
114
+ const SENTENCE_BREAK = /(?<!\b(?:e\.g|i\.e|vs|etc))\.\s+(?=[A-Z`'"(])/;
115
+ const MAX_HINT = 200;
116
+
117
+ /**
118
+ * One-sentence repair instruction for a finding (the shared violation contract's `fix_hint`).
119
+ * Uses `rule.fix` when set; otherwise the message after its first sentence ("Problem. Fix."),
120
+ * falling back to the whole message.
121
+ */
122
+ export function fixHint(rule, message) {
123
+ let hint = rule?.fix;
124
+ if (!hint) {
125
+ const parts = (message ?? "").split(SENTENCE_BREAK);
126
+ hint = parts.length > 1 ? parts.slice(1).join(". ") : message ?? "";
127
+ }
128
+ hint = hint.trim();
129
+ if (hint.length <= MAX_HINT) return hint;
130
+ const cut = hint.slice(0, MAX_HINT - 1);
131
+ return `${cut.slice(0, Math.max(cut.lastIndexOf(" "), 1))}…`;
132
+ }
133
+
134
+ /** Adds the contract fields (`rule_id`, `fix_hint`) without removing the legacy `rule` field. */
135
+ const withContract = (f) => ({ ...f, rule_id: f.rule_id ?? f.rule, fix_hint: f.fix_hint ?? fixHint(null, f.message) });
136
+
114
137
  function lineOf(src, index) {
115
138
  let n = 1;
116
139
  for (let i = 0; i < index && i < src.length; i++) if (src.charCodeAt(i) === 10) n++;
@@ -132,17 +155,20 @@ export function auditSource(raw, file, rules) {
132
155
  for (const rule of rules) {
133
156
  for (const m of matchRule(rule, raw, file)) {
134
157
  const line = lineOf(raw, m.index);
158
+ const message = m.message || rule.message;
135
159
  const finding = {
136
160
  file,
137
161
  line,
138
162
  rule: rule.id,
163
+ rule_id: rule.id,
139
164
  severity: rule.severity,
140
- message: m.message || rule.message,
165
+ message,
166
+ fix_hint: fixHint(rule, message),
141
167
  snippet: (lines[line - 1] ?? m.text ?? "").trim().slice(0, 140),
142
168
  };
143
169
  const s = suppression(lines, line, rule.id);
144
170
  if (s?.reason) suppressed.push({ file, line, rule: rule.id, reason: s.reason });
145
- else if (s) findings.push({ ...finding, severity: "ERROR", rule: "SUPPRESSION_WITHOUT_REASON", message: `unslop-ignore ${rule.id} needs a reason: \`unslop-ignore ${rule.id} -- why this is safe\`.` });
171
+ else if (s) findings.push({ ...finding, severity: "ERROR", rule: "SUPPRESSION_WITHOUT_REASON", rule_id: "SUPPRESSION_WITHOUT_REASON", message: `unslop-ignore ${rule.id} needs a reason: \`unslop-ignore ${rule.id} -- why this is safe\`.`, fix_hint: `Add a reason: \`unslop-ignore ${rule.id} -- why this is safe\`, or fix the finding.` });
146
172
  else findings.push(finding);
147
173
  }
148
174
  }
@@ -157,7 +183,7 @@ export function auditSource(raw, file, rules) {
157
183
  export async function audit(args, root, cfg) {
158
184
  const inputs = Array.isArray(args.files) ? args.files.filter((f) => typeof f === "string" && f) : [];
159
185
  const { files, errors, source } = await collectFiles(inputs, root, cfg.accept);
160
- const findings = [...errors];
186
+ const findings = errors.map(withContract);
161
187
  const suppressed = [];
162
188
  const skippedGenerated = [];
163
189
  const explicit = new Set(inputs.map((f) => path.resolve(root, f)));
@@ -179,6 +205,7 @@ export async function audit(args, root, cfg) {
179
205
  const byRule = {};
180
206
  for (const f of findings) byRule[f.rule] = (byRule[f.rule] || 0) + 1;
181
207
  const failed = errorCount > 0;
208
+ const scanned = files.filter((f) => !skippedGenerated.includes(path.relative(root, f))).map((f) => path.relative(root, f) || path.basename(f));
182
209
  return {
183
210
  status: failed ? "FAIL" : "PASS",
184
211
  filesScanned: files.length - skippedGenerated.length,
@@ -196,6 +223,7 @@ export async function audit(args, root, cfg) {
196
223
  ? "No matching files were scanned. Pass the modified files or directories explicitly."
197
224
  : "All anti-slop checks passed. Review WARN findings before finishing.",
198
225
  _failed: failed,
226
+ _scanned: scanned,
199
227
  };
200
228
  }
201
229
 
package/src/index.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  export { run } from "./server.mjs";
2
- export { audit, auditSource, matchRule, collectFiles, walk, inside, checkRuleExamples, SKIP_DIRS } from "./audit.mjs";
2
+ export { audit, auditSource, matchRule, collectFiles, walk, inside, checkRuleExamples, fixHint, SKIP_DIRS } from "./audit.mjs";
3
3
  export { maskComments, syntaxFor, matchBracket, indentedBlock } from "./mask.mjs";
4
4
  export { runCheck, projectDir, localBin, typescriptCheck, summarizeChecks } from "./exec.mjs";
5
5
  export { installSkills } from "./install.mjs";
6
+ export { createTelemetry, pathHash, TELEMETRY_DIR, TELEMETRY_FILE } from "./telemetry.mjs";
6
7
 
7
8
  /** Builds an `accept` predicate from a list of extensions, e.g. byExt(".ts", ".py"). */
8
9
  export const byExt = (...exts) => {
package/src/server.mjs CHANGED
@@ -12,10 +12,11 @@ import path from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { audit } from "./audit.mjs";
14
14
  import { installSkills } from "./install.mjs";
15
+ import { createTelemetry } from "./telemetry.mjs";
15
16
 
16
17
  const respond = (obj) => {
17
18
  if (typeof obj === "string") return { content: [{ type: "text", text: obj }], isError: false };
18
- const { _failed, ...rest } = obj;
19
+ const { _failed, _scanned, _latencyMs, ...rest } = obj;
19
20
  return { content: [{ type: "text", text: JSON.stringify(rest, null, 2) }], isError: Boolean(_failed) };
20
21
  };
21
22
 
@@ -54,6 +55,7 @@ export async function run(cfg) {
54
55
  return;
55
56
  }
56
57
 
58
+ const telemetry = createTelemetry(pkg.name.replace(/-mcp$/, ""));
57
59
  const server = new Server({ name: pkg.name, version: pkg.version }, { capabilities: { tools: {}, prompts: {} } });
58
60
 
59
61
  server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: [{ name: cfg.skill, description: cfg.description }] }));
@@ -80,7 +82,12 @@ export async function run(cfg) {
80
82
  server.setRequestHandler(CallToolRequestSchema, async (req) => {
81
83
  const { name, arguments: args = {} } = req.params;
82
84
  if (name === loadTool) return respond(await loadSkill());
83
- if (name === cfg.auditTool) return respond(await audit(args, root, cfg));
85
+ if (name === cfg.auditTool) {
86
+ const started = Date.now();
87
+ const result = await audit(args, root, cfg);
88
+ await telemetry.record(root, { ...result, _latencyMs: Date.now() - started });
89
+ return respond(result);
90
+ }
84
91
  const tool = tools.find((t) => t.name === name);
85
92
  if (!tool) throw new Error(`Unknown tool: ${name}`);
86
93
  try {
@@ -96,7 +103,7 @@ export async function run(cfg) {
96
103
  async function cliAudit(argv, root, cfg) {
97
104
  const json = argv.includes("--json");
98
105
  const result = await audit({ files: argv.filter((a) => !a.startsWith("--")) }, root, cfg);
99
- const { _failed, ...rest } = result;
106
+ const { _failed, _scanned, ...rest } = result;
100
107
  if (json) console.log(JSON.stringify(rest, null, 2));
101
108
  else {
102
109
  for (const f of result.findings) console.log(`${f.file}:${f.line} ${f.severity.padEnd(5)} ${f.rule} ${f.message}${f.snippet ? `\n ${f.snippet}` : ""}`);
@@ -0,0 +1,60 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+
5
+ // Opt-in: records are written only when <workspace>/.doctor-unslop/ already exists
6
+ // (`doctor-unslop init` creates it). No source code, messages or snippets are stored.
7
+ export const TELEMETRY_DIR = ".doctor-unslop";
8
+ export const TELEMETRY_FILE = "telemetry.jsonl";
9
+
10
+ /** Hash of the workspace-relative path, so one file keeps one key while its content changes. */
11
+ export const pathHash = (rel) => createHash("sha256").update(rel.split(path.sep).join("/")).digest("hex").slice(0, 16);
12
+
13
+ /**
14
+ * Creates a recorder for one server process. One process is treated as one agent session,
15
+ * because a stdio MCP server is not told the client's session id.
16
+ */
17
+ export function createTelemetry(server, { sessionId = `sess_${randomUUID().slice(0, 8)}`, now = () => new Date() } = {}) {
18
+ const iterations = new Map();
19
+ return {
20
+ sessionId,
21
+ /** Builds one record per scanned file. Pure; exported for tests. */
22
+ records(result) {
23
+ const byFile = new Map();
24
+ for (const f of result.findings ?? []) {
25
+ if (!byFile.has(f.file)) byFile.set(f.file, []);
26
+ byFile.get(f.file).push(f);
27
+ }
28
+ return (result._scanned ?? []).map((file) => {
29
+ const hash = pathHash(file);
30
+ const iteration = (iterations.get(hash) ?? 0) + 1;
31
+ iterations.set(hash, iteration);
32
+ const found = byFile.get(file) ?? [];
33
+ return {
34
+ ts: now().toISOString(),
35
+ session_id: sessionId,
36
+ server,
37
+ file_hash: hash,
38
+ iteration,
39
+ triggered_rules: [...new Set(found.map((f) => f.rule_id ?? f.rule))].sort(),
40
+ passed: !found.some((f) => f.severity === "ERROR"),
41
+ ...(result._latencyMs !== undefined ? { latency_ms: result._latencyMs } : {}),
42
+ };
43
+ });
44
+ },
45
+ /** Appends records when the workspace opted in. Never throws: telemetry must not break an audit. */
46
+ async record(root, result) {
47
+ try {
48
+ const dir = path.join(root, TELEMETRY_DIR);
49
+ const stat = await fs.stat(dir).catch(() => null);
50
+ if (!stat?.isDirectory()) return 0;
51
+ const lines = this.records(result);
52
+ if (!lines.length) return 0;
53
+ await fs.appendFile(path.join(dir, TELEMETRY_FILE), lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
54
+ return lines.length;
55
+ } catch {
56
+ return 0;
57
+ }
58
+ },
59
+ };
60
+ }