diff --git a/CHANGELOG.md b/CHANGELOG.md index f7cd4d1..6a26e9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes will be documented in this file. ## [Unreleased] ### Added +- **The slop index is back, on three axes.** Every rule belongs to one: Noise (information utility), Lies (information quality) or Soul (style and taste). The summary ends with a score per axis and a total, and the JSON report adds `slopIndex` plus an `axis` on every issue and `byType` entry. Unlike the 1.x point total, the scores are per 1,000 lines of application code, so repositories of different sizes compare, and each rule counts logarithmically (`weight × ln(1 + findings per 1,000 lines)`), so one pattern repeated hundreds of times cannot outweigh several different kinds of slop. Package-age warnings from `package.json` are reported but not scored. `customPatterns` take an optional `axis` (default `soul`). `--help` lists each rule's axis. - `--report=` writes the JSON report somewhere other than `./ai-slop-report.json`, and `--no-report` skips it, so a scan no longer has to leave a file in the working tree. - `swallowed_error` (medium): a `catch` block whose only statements are `console` calls. The error is logged and the code carries on as if the operation succeeded. A comment in the block explaining why that is safe, a rethrow, or any other statement (such as `setError(e)`) means it is not reported, and so does a fallback after the `try`, as for `empty_catch`. diff --git a/README.md b/README.md index 12cad62..396e8fe 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![npm downloads](https://img.shields.io/npm/dt/karpeslop.svg)](https://www.npmjs.com/package/karpeslop) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) -A linter for the mistakes AI coding tools tend to leave in TypeScript and JavaScript. +A slop index for TypeScript and JavaScript. KarpeSlop finds the mistakes AI coding tools tend to leave and scores them on three axes: **noise**, **lies** and **soul**. ```bash npx karpeslop@latest @@ -14,17 +14,34 @@ npx karpeslop@latest ## Why -AI tools write code fast, and some of it looks finished when it isn't. Common examples: +AI tools write code fast, and some of it looks finished when it isn't. The idea for KarpeSlop comes from Andrej Karpathy's call for a "slop index": a number that says how much of a codebase is slop, and what kind. KarpeSlop sorts slop into three kinds: -- importing a function the library never had -- importing a package that isn't on npm -- a function body that is just a TODO and `return true` -- `// ... rest of the code` where real code should be -- `catch {}` that hides an error -- reading `res.json()` without checking `res.ok` -- `as any` and other casts that switch off type checking +- **Noise** (information utility): text that adds length without information. Comments that repeat the next line, doc comments that restate parameter names, leftover `console.log`. +- **Lies** (information quality): code that claims to do something it doesn't. A function the library never exported, a package that isn't on npm, a body that is just `return true`, `// ... rest of the code` where real code should be, a `catch {}` that hides the error, `as any` telling the compiler something nobody checked. +- **Soul** (style and taste): shortcuts that show no judgment behind the code. `any`, casts and `!` used to get past the type checker, blanket `eslint-disable`, TODOs nobody is tracking. -ESLint and `tsc` catch some of this. KarpeSlop looks for the rest, so you can find it before it ships. +ESLint and `tsc` catch some of this. KarpeSlop looks for the rest and tells you which kind it is, so you can find it before it ships. + +## The slop index + +Every run ends with a score for each axis. This is a 210,000-line Next.js app: + +``` +Slop index (application code, higher is worse): + Noise information utility 0.6 restating_comment, production_console_log, filler_comment + Lies information quality 7.8 unsafe_object_assertion, unsafe_double_type_assertion, unsafe_array_assertion + Soul style and taste 3.5 type_assertion, non_null_assertion, any_type_usage + Total 11.9 +``` + +KarpeSlop's own source has no findings and scores 0. + +Each rule adds `weight × ln(1 + findings per 1,000 lines)` to its axis, with weights of 8, 4, 2 and 1 for critical, high, medium and low. The scores use findings in application source files only, not tests or `package.json` (so `fresh_package_version` is reported but not scored), and: + +- are per 1,000 lines, so a large repository and a small one can be compared +- grow with the logarithm of each rule's count, so one pattern repeated 500 times can't outweigh five different kinds of slop + +The rules that add the most to each axis are listed next to its score. The JSON report has the full breakdown under `slopIndex`. ## Usage @@ -73,14 +90,13 @@ Add a step to your workflow: ## What it checks -| Severity | Rules | +| Axis | Rules | | --- | --- | -| critical | Imports of names a module doesn't export, files that don't exist, and packages that aren't on npm | -| high | Packages missing from `package.json`, placeholder bodies, elided-code comments, placeholder values like `"YOUR_API_KEY"`, empty `catch` blocks, `as any` and other unsafe casts | -| medium | Errors that are logged and dropped, other casts, `any`, `@ts-ignore`, blanket `eslint-disable`, unchecked `fetch` responses, dependency versions published in the last few days | -| low | `!` assertions, hedging and filler comments, TODOs without an issue link, `console.log` in app code | +| Lies | Imports of names a module doesn't export, files that don't exist, and packages that aren't on npm (critical). Packages missing from `package.json`, placeholder bodies, elided-code comments, placeholder values like `"YOUR_API_KEY"`, empty `catch` blocks, `as any` and other unsafe casts (high). Errors that are logged and dropped, `@ts-ignore`, unchecked `fetch` responses (medium) | +| Soul | Other casts, `any`, blanket `eslint-disable`, dependency versions published in the last few days (medium). `!` assertions, TODOs without an issue link (low) | +| Noise | Hedging, filler and restating comments, `console.log` in app code (low) | -`npx karpeslop@latest --help` lists every rule by name. Test, fixture and example folders are skipped by rules meant for app code. +`npx karpeslop@latest --help` lists every rule with its severity and axis. Test, fixture and example folders are skipped by rules meant for app code. ## Configuration @@ -100,7 +116,8 @@ Add a `.karpesloprc.json` to your project root: "id": "banned_import", "pattern": "from\\s+['\"]lodash['\"]", "message": "Use lodash-es", - "severity": "medium" + "severity": "medium", + "axis": "soul" } ] } @@ -110,7 +127,7 @@ Add a `.karpesloprc.json` to your project root: - `ignorePaths` skips files that match these globs. - `minPackageAgeDays` sets how new a dependency version has to be before it gets flagged. - `blockOnCritical` acts like `--strict` on every run. -- `customPatterns` adds your own regex rules, matched one line at a time. +- `customPatterns` adds your own regex rules, matched one line at a time. `axis` is `noise`, `lies` or `soul` (the default, since a custom pattern usually records your team's taste). There are no inline comments to silence a finding. Changes go in this file so they show up in code review. diff --git a/ai-slop-detector.ts b/ai-slop-detector.ts index 15ab869..3d82384 100644 --- a/ai-slop-detector.ts +++ b/ai-slop-detector.ts @@ -14,6 +14,7 @@ import path from 'path'; import { glob } from 'glob'; import { fileURLToPath } from 'url'; import { + AXES, RULES, analyzeSource, findUnsafeAssertions, @@ -21,6 +22,7 @@ import { isExamplePath, isFixturePath, isNonProductionPath, + type Axis, type Severity, type UnsafeAssertionFinding } from './rules.ts'; @@ -33,9 +35,12 @@ const SEVERITIES: readonly Severity[] = ['critical', 'high', 'medium', 'low']; const OVERRIDE_SEVERITIES: ReadonlyArray = [...SEVERITIES, 'off']; /** Every rule id KarpeSlop reports itself. fresh_package_version comes from the registry check, not RULES. */ const BUILT_IN_RULE_IDS: ReadonlySet = new Set([...RULES.map(rule => rule.id), 'fresh_package_version']); +/** Installing a version days after it was published is a judgment call, not a defect in the code. */ +const FRESH_PACKAGE_AXIS: Axis = 'soul'; interface AISlopIssue { type: string; + axis: Axis; file: string; line: number; column: number; @@ -47,6 +52,7 @@ interface AISlopIssue { interface ConsolidatedIssue { type: string; + axis: Axis; file: string; code: string; message: string; @@ -59,6 +65,7 @@ interface DetectionPattern { pattern: RegExp; message: string; severity: Severity; + axis: Axis; fix?: string; learnMore?: string; } @@ -68,6 +75,8 @@ interface CustomPatternConfig { pattern: string; message: string; severity: Severity; + /** Which axis of the slop index the pattern scores on. Defaults to soul: a custom pattern usually encodes a team's taste. */ + axis?: Axis; description?: string; fix?: string; learnMore?: string; @@ -88,6 +97,10 @@ interface ScanSummary { applicationLinesScanned: number; } +function isAxis(value: unknown): value is Axis { + return AXES.some(axis => axis.id === value); +} + function isSeverity(value: unknown): value is Severity { return SEVERITIES.some(severity => severity === value); } @@ -188,6 +201,54 @@ export function exitCodeFor(issues: ReadonlyArray issue.type !== 'fresh_package_version' && SEVERITIES.indexOf(issue.severity) <= threshold) ? 1 : 0; } +const SEVERITY_WEIGHTS: Record = { critical: 8, high: 4, medium: 2, low: 1 }; + +export interface SlopIndexRule { + type: string; + findings: number; + points: number; +} + +export interface SlopIndex { + /** Lines of application code the scores are relative to. */ + applicationLines: number; + axes: Array<{ axis: Axis; score: number; rules: SlopIndexRule[] }>; + total: number; +} + +/** + * Scores application-code findings on the three axes. Each rule adds + * `weight(severity) * ln(1 + findings per 1,000 lines)` to its axis: per 1,000 + * lines so repositories of different sizes compare, and logarithmic so one + * rule repeated hundreds of times cannot outweigh several different kinds of + * slop. A rule's weight is that of its most severe finding. + */ +export function slopIndex( + findings: ReadonlyArray>, + applicationLines: number +): SlopIndex { + const byRule = new Map(); + for (const finding of findings) { + const entry = byRule.get(finding.type) ?? { axis: finding.axis, findings: 0, weight: 0 }; + entry.findings++; + entry.weight = Math.max(entry.weight, SEVERITY_WEIGHTS[finding.severity]); + byRule.set(finding.type, entry); + } + const round = (n: number) => Math.round(n * 100) / 100; + const axes = AXES.map(({ id }) => { + const rules = [...byRule.entries()] + .filter(([, entry]) => entry.axis === id) + .map(([type, entry]) => ({ + type, + findings: entry.findings, + points: applicationLines > 0 ? round(entry.weight * Math.log1p((entry.findings * 1000) / applicationLines)) : 0 + })) + .sort((a, b) => b.points - a.points || a.type.localeCompare(b.type)); + return { axis: id, score: round(rules.reduce((sum, rule) => sum + rule.points, 0)), rules }; + }); + return { applicationLines, axes, total: round(axes.reduce((sum, axis) => sum + axis.score, 0)) }; +} + /** A path.relative() result outside the root: `../x`, or on Windows a path on another drive (`D:\\x`). */ export function leavesRoot(relativePath: string): boolean { return relativePath === '..' || /^\.\.[\\/]/.test(relativePath) || path.isAbsolute(relativePath); @@ -366,6 +427,9 @@ class AISlopDetector { if (!isSeverity(severity)) { throw new Error(`customPatterns[${i}].severity must be one of: ${SEVERITIES.join(', ')}`); } + if (pattern.axis !== undefined && !isAxis(pattern.axis)) { + throw new Error(`customPatterns[${i}].axis must be one of: ${AXES.map(axis => axis.id).join(', ')}`); + } try { new RegExp(source, 'gi'); } catch { @@ -376,6 +440,7 @@ class AISlopDetector { pattern: source, message, severity, + axis: isAxis(pattern.axis) ? pattern.axis : undefined, description: optionalString(pattern.description), fix: optionalString(pattern.fix), learnMore: optionalString(pattern.learnMore) @@ -450,6 +515,7 @@ class AISlopDetector { ? `${customPattern.message} (${customPattern.description})` : customPattern.message, severity: customPattern.severity, + axis: customPattern.axis ?? 'soul', fix: customPattern.fix, learnMore: customPattern.learnMore }); @@ -639,10 +705,14 @@ class AISlopDetector { return uniqueRealFiles(resolved); } - private record(issue: Omit, defaultSeverity: Severity): void { + private record(issue: Omit, defaultSeverity: Severity): void { const severity = this.severityOf(issue.type, defaultSeverity); if (severity === 'off') return; - this.issues.push({ ...issue, severity }); + this.issues.push({ ...issue, severity, axis: this.axisOf(issue.type) }); + } + + private axisOf(ruleId: string): Axis { + return getRule(ruleId)?.axis ?? this.customPatterns.find(pattern => pattern.id === ruleId)?.axis ?? FRESH_PACKAGE_AXIS; } /** @@ -964,7 +1034,7 @@ class AISlopDetector { const counts = SEVERITIES.map(severity => `${this.issues.filter(issue => issue.severity === severity).length} ${severity}`); const files = new Set(this.issues.map(issue => issue.file)).size; const { applicationLinesScanned } = this.summary; - const applicationFindings = this.issues.filter(issue => this.lineCounts.has(issue.file) && !this.isNonProductionFile(issue.file)).length; + const applicationFindings = this.applicationIssues().length; const density = applicationLinesScanned > 0 ? `, ${((applicationFindings / applicationLinesScanned) * 1000).toFixed(1)} per 1,000 lines of application code` : ''; @@ -972,9 +1042,31 @@ class AISlopDetector { if (hasOnlyFreshPackageWarnings(this.issues)) { console.log('Only package-age warnings were found.'); } + if (applicationLinesScanned > 0) this.printSlopIndex(); console.log('To turn a rule off or change its severity, use severityOverrides in .karpesloprc.json.'); } + /** Findings in application code: the ones finding density and the slop index count. */ + private applicationIssues(): AISlopIssue[] { + return this.issues.filter(issue => this.lineCounts.has(issue.file) && !this.isNonProductionFile(issue.file)); + } + + getSlopIndex(): SlopIndex { + return slopIndex(this.applicationIssues(), this.summary.applicationLinesScanned); + } + + private printSlopIndex(): void { + const index = this.getSlopIndex(); + console.log('\nSlop index (application code, higher is worse):'); + const names = new Map(AXES.map(entry => [entry.id, entry])); + for (const { axis, score, rules } of index.axes) { + const { name, label } = names.get(axis) ?? { name: axis, label: '' }; + const top = rules.slice(0, 3).map(rule => rule.type).join(', '); + console.log(` ${name.padEnd(6)} ${label.padEnd(20)} ${score.toFixed(1).padStart(6)}${top ? ` ${top}` : ''}`); + } + console.log(` ${'Total'.padEnd(27)} ${index.total.toFixed(1).padStart(6)}\n`); + } + /** * Get the current configuration */ @@ -1012,6 +1104,7 @@ class AISlopDetector { } else { issueMap.set(key, { type: issue.type, + axis: issue.axis, file: issue.file, code: issue.code, message: issue.message, @@ -1053,8 +1146,10 @@ class AISlopDetector { uniqueIssues: consolidatedIssues.length, totalOccurrences: countOccurrences(consolidatedIssues), bySeverity, + slopIndex: this.getSlopIndex(), byType: Array.from(byTypeMap.entries()).map(([type, issues]) => ({ type, + axis: issues[0].axis, occurrences: countOccurrences(issues), uniqueIssues: issues.length, sample: issues.slice(0, 3).map(issue => ({ @@ -1082,7 +1177,8 @@ export function splitCliArgs(args: readonly string[]): { flagArgs: string[]; tar } function printHelp(): void { - const ruleLines = RULES.map(rule => ` ${rule.id.padEnd(30)} ${rule.severity.padEnd(9)} ${rule.message}`); + const ruleLines = RULES.map(rule => ` ${rule.id.padEnd(30)} ${rule.severity.padEnd(9)} ${rule.axis.padEnd(6)} ${rule.message}`); + const axisLines = AXES.map(axis => ` ${axis.id.padEnd(6)} ${axis.name} (${axis.label})`); console.log(` Usage: karpeslop [options] [path...] @@ -1105,9 +1201,13 @@ Exit codes: 1 - Findings at the --fail-on severity (default high) or above 2 - Critical findings (--strict only) -Rules: +Slop index: + Findings in application code are scored on three axes, per 1,000 lines: +${axisLines.join('\n')} + +Rules (id, severity, axis): ${ruleLines.join('\n')} - ${'fresh_package_version'.padEnd(30)} ${'medium'.padEnd(9)} Dependency version was published very recently. + ${'fresh_package_version'.padEnd(30)} ${'medium'.padEnd(9)} ${FRESH_PACKAGE_AXIS.padEnd(6)} Dependency version was published very recently. Inline suppression comments are not supported. Change a rule's severity, or turn it off, with severityOverrides in .karpesloprc.json. diff --git a/codemeta.json b/codemeta.json index 79635e8..b8fa170 100644 --- a/codemeta.json +++ b/codemeta.json @@ -2,7 +2,7 @@ "@context": "https://raw.githubusercontent.com/codemeta/codemeta/2.0/codemeta.jsonld", "@type": "SoftwareSourceCode", "name": "KarpeSlop", - "description": "A linter for the mistakes AI coding tools leave in TypeScript and JavaScript: imports that don't exist, missing packages, placeholder code, swallowed errors and unsafe casts.", + "description": "A slop index for TypeScript and JavaScript: finds the mistakes AI coding tools leave (imports that don't exist, placeholder code, swallowed errors, unsafe casts) and scores them on three axes: noise, lies and soul.", "version": "2.0.0", "license": "https://spdx.org/licenses/MIT.html", "codeRepository": "https://github.com/CodeDeficient/karpeslop", diff --git a/package.json b/package.json index 4240444..4e8ccfa 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "karpeslop", "version": "2.0.0", - "description": "A linter for the mistakes AI coding tools leave in TypeScript and JavaScript: imports that don't exist, missing packages, placeholder code, swallowed errors and unsafe casts.", + "description": "A slop index for TypeScript and JavaScript: finds the mistakes AI coding tools leave (imports that don't exist, placeholder code, swallowed errors, unsafe casts) and scores them on three axes: noise, lies and soul.", "type": "module", "packageManager": "npm@10.9.7", "bin": { diff --git a/rules.ts b/rules.ts index d917c75..7ff2645 100644 --- a/rules.ts +++ b/rules.ts @@ -12,9 +12,24 @@ import ts from 'typescript'; export type Severity = 'critical' | 'high' | 'medium' | 'low'; +/** + * The three kinds of slop the index scores: + * - noise: text that adds length without information (Information Utility) + * - lies: code that claims to do something it doesn't (Information Quality) + * - soul: shortcuts that show no judgment behind the code (Style / Taste) + */ +export type Axis = 'noise' | 'lies' | 'soul'; + +export const AXES: ReadonlyArray<{ id: Axis; name: string; label: string }> = [ + { id: 'noise', name: 'Noise', label: 'information utility' }, + { id: 'lies', name: 'Lies', label: 'information quality' }, + { id: 'soul', name: 'Soul', label: 'style and taste' } +]; + export interface RuleInfo { id: string; severity: Severity; + axis: Axis; /** One-line statement of what was found. Neutral: says nothing about who wrote it. */ message: string; /** Why it matters, or what to check. */ @@ -40,6 +55,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'hallucinated_import', severity: 'critical', + axis: 'lies', message: 'Imported name is not exported by the module.', why: 'This import fails at build time or is undefined at runtime.', learnMore: 'https://www.typescriptlang.org/docs/handbook/modules/reference.html' @@ -47,6 +63,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'nonexistent_package', severity: 'critical', + axis: 'lies', message: 'Imported package does not exist on the npm registry.', why: 'Names that models invent are a known target for package squatting. Do not install a package with this name without checking who published it.', fix: 'Remove the import and use a package you have verified.' @@ -54,6 +71,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'undeclared_dependency', severity: 'high', + axis: 'lies', message: 'Imported package is not declared in package.json and is not installed.', why: 'The import cannot resolve on a clean install.', fix: 'Add the package to package.json if it is the one you meant, or remove the import.' @@ -61,6 +79,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'placeholder_implementation', severity: 'high', + axis: 'lies', message: 'Function body is a placeholder.', why: 'The function returns a dummy value or throws instead of doing its job, so callers get wrong results without an error.', skipTests: true @@ -68,6 +87,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'elided_code_comment', severity: 'high', + axis: 'lies', message: 'Comment stands in for code that was left out ("... rest of code").', why: 'Code was elided, usually when a snippet was pasted from a chat answer. Whatever it stood for is missing.', fix: 'Restore the omitted code or delete the comment if nothing is missing.' @@ -75,6 +95,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'placeholder_value', severity: 'high', + axis: 'lies', message: 'String literal is a placeholder value (e.g. "YOUR_API_KEY").', why: 'The real value was never filled in. It usually belongs in configuration or an environment variable.', skipTests: true @@ -82,6 +103,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'empty_catch', severity: 'high', + axis: 'lies', message: 'Error is caught and silently discarded.', why: 'Failures here leave no trace. If ignoring the error is intended, say why in a comment inside the block.', learnMore: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch', @@ -90,6 +112,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'swallowed_error', severity: 'medium', + axis: 'lies', message: 'Error is caught, logged and then discarded.', why: 'Execution continues as if the operation succeeded, so callers and users never learn it failed. Rethrow, return a result the caller checks, or say in a comment why continuing is safe.', learnMore: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch', @@ -98,6 +121,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'unsafe_type_assertion', severity: 'high', + axis: 'lies', message: "Value is cast to 'any'.", why: 'The cast turns off type checking for every later use of the value.', learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates', @@ -106,6 +130,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'unsafe_double_type_assertion', severity: 'high', + axis: 'lies', message: 'Value is cast through another type (e.g. "as unknown as T").', why: 'A chained cast forces a conversion the compiler rejected. Validate the value at runtime or fix the source type instead.', learnMore: 'https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions', @@ -114,6 +139,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'unsafe_object_assertion', severity: 'high', + axis: 'lies', message: 'Value is cast to an object type.', why: 'The compiler takes the shape on trust. If the value comes from outside the program (JSON, an API, storage), validate it instead.', learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html', @@ -122,6 +148,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'unsafe_array_assertion', severity: 'high', + axis: 'lies', message: 'Value is cast to an array type.', why: 'The compiler takes the element type on trust. If the value comes from outside the program, validate it instead.', learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html', @@ -130,6 +157,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'type_assertion', severity: 'medium', + axis: 'soul', message: 'Value is cast to another type.', why: 'The compiler takes the target type on trust. Prefer a type guard, a typed source, or "satisfies" when you only need to check the shape.', learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html', @@ -138,6 +166,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'any_type_usage', severity: 'medium', + axis: 'soul', message: "Type is declared as 'any'.", why: "'any' turns off type checking wherever the value flows. 'unknown' keeps it on and forces a check before use.", learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html', @@ -146,6 +175,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'ts_suppression', severity: 'medium', + axis: 'lies', message: 'Type errors are suppressed with @ts-ignore or @ts-nocheck.', why: 'The suppression hides the error permanently, including after the code around it changes.', fix: "Use '// @ts-expect-error ' for a single line; it fails once the error is gone.", @@ -154,6 +184,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'blanket_eslint_disable', severity: 'medium', + axis: 'soul', message: 'ESLint is disabled without naming a rule.', why: 'Every lint rule is off for this scope, not just the one that fired.', fix: 'Name the rule being disabled, e.g. "eslint-disable-next-line no-console".' @@ -161,6 +192,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'unchecked_fetch_response', severity: 'medium', + axis: 'lies', message: 'fetch() response body is read without checking the HTTP status.', why: 'fetch() only rejects on network failure. A 404 or 500 response is read as if it succeeded.', fix: 'Check response.ok (or response.status) before reading the body.', @@ -170,6 +202,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'non_null_assertion', severity: 'low', + axis: 'soul', message: "Non-null assertion ('!') on a value.", why: 'The compiler takes it on trust that the value is not null or undefined. Check it or narrow the type instead.', learnMore: 'https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-', @@ -178,6 +211,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'hedging_comment', severity: 'low', + axis: 'noise', message: 'Comment says the code is unverified ("should work", "hopefully").', why: 'Check the behavior and record what you found, or add a test.', skipTests: true @@ -185,6 +219,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'restating_comment', severity: 'low', + axis: 'noise', message: 'Comment restates the next line of code.', why: 'It repeats what the code already says. Comments are most useful when they explain why.', skipTests: true @@ -192,6 +227,7 @@ export const RULES: readonly RuleInfo[] = [ { id: 'filler_comment', severity: 'low', + axis: 'noise', message: 'Doc comment restates names ("@param id - the id", "@returns the result", "This function is used to ...").', why: 'It adds length without information. Say what is not obvious from the name, or remove it.', skipTests: true @@ -199,12 +235,14 @@ export const RULES: readonly RuleInfo[] = [ { id: 'todo_comment', severity: 'low', + axis: 'soul', message: 'TODO/FIXME/HACK marker.', why: 'Unfinished work. Link a tracking issue so it is not forgotten.' }, { id: 'production_console_log', severity: 'low', + axis: 'noise', message: 'console.log/debug/info call in application code.', why: 'Usually leftover debugging output. Use your logger if the output is intended.', skipTests: true diff --git a/tests/ai-slop-detector.behavior.test.ts b/tests/ai-slop-detector.behavior.test.ts index 87db2be..775f53d 100644 --- a/tests/ai-slop-detector.behavior.test.ts +++ b/tests/ai-slop-detector.behavior.test.ts @@ -18,6 +18,7 @@ import { pLimit, reportPathFrom, shouldAnalyzePathInQuietMode, + slopIndex, splitCliArgs, uniqueRealFiles, unknownFlags, @@ -904,3 +905,77 @@ test('an invalid config stops the run with exit 1 instead of falling back to def assert.match(result.stderr, /KarpeSlop: Invalid config at .*\.karpesloprc\.json: customPatterns\[0\]\.severity must be one of/); assert.doesNotMatch(result.stdout, /Scanning/); }); + +test('slop index scores per 1,000 lines, so repositories of different sizes compare', () => { + const findings = (count: number) => Array.from({ length: count }, () => ({ type: 'empty_catch', axis: 'lies' as const, severity: 'high' as const })); + const small = slopIndex(findings(2), 1_000); + const large = slopIndex(findings(200), 100_000); + assert.equal(small.total, large.total); + // weight 4 (high) * ln(1 + 2 per 1,000 lines) + assert.equal(small.axes.find(axis => axis.axis === 'lies')?.score, Math.round(4 * Math.log1p(2) * 100) / 100); + assert.deepEqual(small.axes.map(axis => axis.axis), ['noise', 'lies', 'soul']); + assert.equal(slopIndex(findings(3), 0).total, 0); +}); + +test('slop index: five kinds of slop outscore one rule repeated as often', () => { + const lines = 10_000; + const repeated = slopIndex(Array.from({ length: 100 }, () => ({ type: 'type_assertion', axis: 'soul' as const, severity: 'medium' as const })), lines); + const varied = slopIndex(['type_assertion', 'any_type_usage', 'non_null_assertion', 'blanket_eslint_disable', 'todo_comment'] + .flatMap(type => Array.from({ length: 20 }, () => ({ type, axis: 'soul' as const, severity: 'medium' as const }))), lines); + assert.ok(varied.total > repeated.total, `varied ${varied.total} should exceed repeated ${repeated.total}`); + const soul = repeated.axes.find(axis => axis.axis === 'soul'); + assert.deepEqual(soul?.rules, [{ type: 'type_assertion', findings: 100, points: soul?.score }]); +}); + +test('the report and summary give each finding an axis and print the slop index', async t => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'karpeslop-index-')); + try { + fs.writeFileSync(path.join(dir, '.karpesloprc.json'), JSON.stringify({ + customPatterns: [ + { id: 'no_lodash', pattern: "from 'lodash'", message: 'Use lodash-es', severity: 'low' }, + { id: 'no_mock_data', pattern: 'MOCK_DATA', message: 'Mock data in app code', severity: 'high', axis: 'lies' } + ] + })); + fs.writeFileSync(path.join(dir, 'app.ts'), [ + "import _ from 'lodash';", + 'export const rows = MOCK_DATA;', + 'export function load() {', + ' try { return JSON.parse("{}"); } catch {}', + '}', + '' + ].join('\n')); + const log = t.mock.method(console, 'log', () => {}); + const detector = new AISlopDetector(dir, undefined, async () => 'exists'); + await detector.detect(); + const output = log.mock.calls.map(call => String(call.arguments[0])).join('\n'); + assert.match(output, /Slop index \(application code, higher is worse\):/); + const lies = output.split('\n').find(line => /^ +Lies +information quality +\d+\.\d/.test(line)) ?? ''; + assert.match(lies, /\bempty_catch\b/); + assert.match(lies, /\bno_mock_data\b/); + assert.match(output, /Soul +style and taste +\d+\.\d .*\bno_lodash\b/); + const report = path.join(dir, 'report.json'); + detector.exportResults(report); + const parsed = JSON.parse(fs.readFileSync(report, 'utf8')); + const axisOf = (type: string) => parsed.issues.find((issue: { type: string }) => issue.type === type)?.axis; + assert.equal(axisOf('empty_catch'), 'lies'); + assert.equal(axisOf('no_mock_data'), 'lies'); + assert.equal(axisOf('no_lodash'), 'soul'); + assert.equal(parsed.slopIndex.applicationLines, 5); + assert.deepEqual(parsed.slopIndex.axes.map((axis: { axis: string }) => axis.axis), ['noise', 'lies', 'soul']); + assert.equal(parsed.byType.find((entry: { type: string }) => entry.type === 'empty_catch')?.axis, 'lies'); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('a custom pattern with an unknown axis is an invalid config', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'karpeslop-axis-')); + try { + fs.writeFileSync(path.join(dir, '.karpesloprc.json'), JSON.stringify({ + customPatterns: [{ id: 'x', pattern: 'x', message: 'm', severity: 'low', axis: 'taste' }] + })); + assert.throws(() => new AISlopDetector(dir), /customPatterns\[0\]\.axis must be one of: noise, lies, soul/); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +});